gpt4 book ai didi

reactjs - 使用 Jest/Enzyme 测试延迟的自定义 React 钩子(Hook)?

转载 作者:行者123 更新时间:2023-12-04 04:17:06 27 4
gpt4 key购买 nike

我正在尝试测试使用 useStateuseEffect 以及模拟延迟加载某些数据的 setTimeout 的自定义 Hook 。简化

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 测试此 Hook 的所有可能状态(加载、错误和值)?

提前致谢!!!

最佳答案

我想您真正想要的是在 useEffect Hook 中发送 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');
});
});

这是供引用的 repo 协议(protocol):https://github.com/oahehc/stackoverflow-answers/tree/60514934/src

此外,您将 id 传递给 useCustomHook,我猜这将用作 API 请求中的参数。因此,您可能希望添加更多测试用例来检查该部分。

关于reactjs - 使用 Jest/Enzyme 测试延迟的自定义 React 钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60514934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com