Reactjs 用Jest/酶测试延迟定制反应挂钩?
我正在尝试测试一个自定义钩子,它使用Reactjs 用Jest/酶测试延迟定制反应挂钩?,reactjs,typescript,jestjs,react-hooks,enzyme,Reactjs,Typescript,Jestjs,React Hooks,Enzyme,我正在尝试测试一个自定义钩子,它使用useState和useffect以及一个setTimeout来模拟加载一些数据的延迟。简化 const useCustomHook=(id:number)=>{ 常量[loading,setLoading]=React.useState(true); const[error,setError]=React.useState(false); const[value,setValue]=React.useState(); React.useffect(()=>{
useState
和useffect
以及一个setTimeout
来模拟加载一些数据的延迟。简化
const useCustomHook=(id:number)=>{
常量[loading,setLoading]=React.useState(true);
const[error,setError]=React.useState(false);
const[value,setValue]=React.useState();
React.useffect(()=>{
常量虚拟=[“foo”、“bar”、“baz”];
//模拟带延迟的远程呼叫
设置超时(()=>{
id<3?设置值(虚拟[id]):设置错误(真);
设置加载(假);
}, 1500);
},[id]);
返回[加载、错误、值];
};
常量应用=()=>{
const[load,error,value]=useCustomHook(1);
如果(加载){返回加载…;}
if(error){返回错误;}
返回{value};
};
您将如何使用Jest和Ezyme测试这个钩子的所有可能状态(加载、错误和值)
提前感谢 我猜您真正想要的是在
useffect
钩子中发送一个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');
});
});
description('App',()=>{
在每个之前(()=>{
fetch.resetMocks();
});
它('应该获取请求',异步()=>{
等待动作(异步()=>{
等待上山(
此外,您将id
传递到useCustomHook
,我想这将用作API请求中的参数。因此您可能需要添加更多测试用例来检查该部分。这可能是要阅读的页面