如何使用 Jest 和 React 测试库模拟从自定义挂钩返回的函数
我在测试使用自定义挂钩的组件时遇到问题。我为“Spinner”编写了一个自定义挂钩,它在内部使用上下文向组件提供微调器状态。
然后,我在内部使用了 useSpinner()
,例如登录表单组件。我收到下面提到的错误。这里的测试运行也没有失败。
未捕获的 TypeError setLoading 不是函数
。
Login.tsx
...
const [loading, setLoading] = useSpinner();
const clearForm = useCallback(() => {
setEmail('');
setPassword('');
setLoading(false); /* Getting error here */
}, [setLoading]);
useEffect(() => () => clearForm(), [clearForm]);
...
use-spinner.tsx
export default function useSpinner(): SpinnerContextType {
const context = useContext(SpinnerContext);
if (!context) {
throw new Error('useSpinner is used outside of SpinnerContext scope');
}
return context;
}
在我的 types.ts
文件中,我定义了类型 SpinnerContextType
export type SpinnerContextType = [
loading: boolean,
setLoading: (value: boolean) => void
];
并SpinnerContext.tsx
文件包含
const SpinnerContext = createContext<SpinnerContextType>([false, null]);
在我的测试文件 Login.test.tsx
中,我为此创建了一个模拟。但这没有用。
const setLoadingMock = jest.fn((v: boolean) => {});
jest.mock('../../hooks/use-spinner', () => ({
__esModule: true,
default: [false, setLoadingMock],
}));
test('Test login', () => {
render(
<SpinnerContext.Provider value={[false, setLoadingMock]}>
<Login />
</SpinnerContext.Provider>
);
});
I'm facing problem while testing a component that uses custom hook. I have written a custom hook for "Spinner" that internally uses a context to provide the spinner state to the components.
Then, I used useSpinner()
inside, say for eg, Login form component. I'm getting the below mentioned error. Also the test run didn't fail here.
uncaught TypeError setLoading is not a function
.
Login.tsx
...
const [loading, setLoading] = useSpinner();
const clearForm = useCallback(() => {
setEmail('');
setPassword('');
setLoading(false); /* Getting error here */
}, [setLoading]);
useEffect(() => () => clearForm(), [clearForm]);
...
use-spinner.tsx
export default function useSpinner(): SpinnerContextType {
const context = useContext(SpinnerContext);
if (!context) {
throw new Error('useSpinner is used outside of SpinnerContext scope');
}
return context;
}
In my types.ts
file, I have defined the type SpinnerContextType
export type SpinnerContextType = [
loading: boolean,
setLoading: (value: boolean) => void
];
and SpinnerContext.tsx
file contains
const SpinnerContext = createContext<SpinnerContextType>([false, null]);
In my test file Login.test.tsx
, I have created a mock for this. But it didn't work.
const setLoadingMock = jest.fn((v: boolean) => {});
jest.mock('../../hooks/use-spinner', () => ({
__esModule: true,
default: [false, setLoadingMock],
}));
test('Test login', () => {
render(
<SpinnerContext.Provider value={[false, setLoadingMock]}>
<Login />
</SpinnerContext.Provider>
);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论