我正在尝试测试一个自定义挂钩,该挂钩使用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测试这个钩子的所有可能状态(加载、错误和值(?
提前感谢!!!
我猜您真正想要的是在useEffect
挂钩中发送一个API请求。(如果我误解了你的目的,很抱歉(
如果是,我将检查
- API请求已发送
- 首先显示加载
- 当API请求失败时显示错误
- 当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请求中的参数。因此,您可能需要添加更多的测试用例来检查该部分。