我正在尝试测试使用useState
和useEffect
以及模拟延迟加载某些数据的setTimeout
的自定义钩子。简化
const useCustomHook = (id: number) => {
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(false);
const [value, setValue] = React.useState<string>();
React.useEffect(() => {
const dummy = ["foo", "bar", "baz"];
// simulate remote call with delay
setTimeout(() => {
id < 3 ? setValue(dummy[id]) : setError(true);
setLoading(false);
}, 1500);
}, [id]);
return [loading, error, value];
};
const App = () => {
const [loading, error, value] = useCustomHook(1);
if (loading) { return <div>Loading...</div>; }
if (error) { return <div>Error</div>; }
return <h1>{value}</h1>;
};
https://codesandbox.io/s/react-typescript-z1z2b
您如何使用Jest和Enzyme测试该挂钩的所有可能状态(加载,错误和值)?
提前谢谢!!!
答案 0 :(得分:0)
我想您真正想要的是在useEffect
挂钩内发送API请求。 (对不起,如果我误解了您的意图)
如果是,我会检查
测试应如下所示。
describe('App', () => {
beforeEach(() => {
fetch.resetMocks();
});
it('should fetch the request', async () => {
await act(async () => {
await mount(<App />)
})
expect(fetch).toBeCalledWith('https://dog.ceo/api/breeds/image/random');
});
it('should show loading at first', () => {
// mock useEffect to test the status before the API request
jest
.spyOn(React, 'useEffect')
.mockImplementationOnce(() => {});
const comp = mount(<App />)
expect(comp.text()).toBe('Loading...');
});
it('should display error if api request fail', async () => {
fetch.mockRejectOnce();
let comp;
await act(async () => {
comp = await mount(<App />);
})
comp.update();
expect(comp.text()).toBe('Error');
});
it('should display result if api request success', async () => {
fetch.mockResponseOnce(JSON.stringify({
message: "https://images.dog.ceo/breeds/mastiff-tibetan/n02108551_1287.jpg",
status: "success"
}));
let comp;
await act(async () => {
comp = await mount(<App />);
})
comp.update();
expect(comp.find('img')).toHaveLength(1);
expect(comp.find('img').prop('src'))
.toBe('https://images.dog.ceo/breeds/mastiff-tibetan/n02108551_1287.jpg');
});
});
以下是供参考的存储库:https://github.com/oahehc/stackoverflow-answers/tree/60514934/src
此外,您将id
传递到useCustomHook
中,我想这将用作API请求中的参数。因此,您可能想添加更多测试用例来检查该部分。