reactjs - React 测试库 - 使用 React.context 测试钩子
问题描述
我对带有自定义钩子的 react-testing-library 有疑问
当我在自定义钩子中使用上下文时,我的测试似乎通过了,但是当我在钩子清理函数中更新上下文值而不通过时。那么有人可以解释为什么这是或不是测试自定义钩子的好方法吗?
提供者和钩子代码:
// component.tsx
import * as React from "react";
const CountContext = React.createContext({
count: 0,
setCount: (c: number) => {},
});
export const CountProvider = ({ children }) => {
const [count, setCount] = React.useState(0);
const value = { count, setCount };
return <CountContext.Provider value={value}>{children}</CountContext.Provider>;
};
export const useCount = () => {
const { count, setCount } = React.useContext(Context);
React.useEffect(() => {
return () => setCount(50);
}, []);
return { count, setCount };
};
测试代码:
// component.spec.tsx
import * as React from "react";
import { act, render, screen } from "@testing-library/react";
import { CountProvider, useCount } from "./component";
describe("useCount", () => {
it("should save count when unmount and restore count", () => {
const Wrapper = ({ children }) => {
return <ContextStateProvider>{children}</ContextStateProvider>;
};
const Component = () => {
const { count, setCount } = useCount();
return (
<div>
<div data-testid="foo">{count}</div>
</div>
);
};
const { unmount, rerender, getByTestId, getByText } = render(
<Component />, { wrapper: Wrapper }
);
expect(getByTestId("foo").textContent).toBe("0");
unmount();
rerender(<Component />);
// I Expected: "50" but Received: "0". but I dont understand why
expect(getByTestId("foo").textContent).toBe("50");
});
});
解决方案
推荐阅读
- python - Python作业与while循环打印输出
- html - Reactjs - 调整大小时排序div
- android-gradle-plugin - 两台机器上相同输入的不同 proguard 输出
- python - 遍历目录以搜索两个可能的匹配文件
- java - 在 Java 程序中使用 JDBC 驱动程序是否可以在没有反射的情况下工作?
- javascript - PhantomJS 屏幕截图中缺少数据
- javascript - Angular 发射父子组件
- angularjs - 从 ZIP 中提取的文件在重新保存之前无法识别
- delphi - Delphi FMX PaintTo() 在不同的文件中
- graphql - graphql - 查询多个表