Reactjs 如何在useEffect中测试异步函数的基本示例

Reactjs 如何在useEffect中测试异步函数的基本示例,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我有一个简单的组件,它获取异步的帖子列表 export const Posts=()=>{ const[list,dispatch]=useReducer(listReducer,[]); useffect(()=>{ 获取列表(调度); }, []); 返回( {list.map((el)=>( {el.title} ))} ); }; 在另一个文件中,我保留了以下逻辑: export const fetchList = async (dispatch) => { try {

我有一个简单的组件,它获取异步的帖子列表

export const Posts=()=>{
const[list,dispatch]=useReducer(listReducer,[]);
useffect(()=>{
获取列表(调度);
}, []);
返回(
    {list.map((el)=>(
  • {el.title}
  • ))}
); };
在另一个文件中,我保留了以下逻辑:

export const fetchList = async (dispatch) => {
  try {
    const result = await api.get('/list/') /* AXIOS */
    dispatch({ type: LIST_SUCCES, payload: result.data.list })
  } catch (error) {
    dispatch({ type: LIST_FAILURE })
  }
}

export const listReducer = (state, action) => {
  switch (action.type) {
    case LIST_SUCCES: 
      return action.payload
    case LIST_FAILURE:
      return []
    default:
      throw new Error()
  }
}

我尝试了多个库,但我无法编写测试。如何编写
Posts.test.js
来检查post是否被提取和显示,我在第一次装入组件后触发异步
fetchList
(因此它不是
componentDidMount
),在提取数据后,我从该异步函数中调度操作并更新列表。

以下是单元测试解决方案:

index.tsx

import React,{useReducer,useffect}来自“React”;
从“/reducer”导入{listReducer,fetchList};
导出常量帖子=()=>{
const[list,dispatch]=useReducer(listReducer,[]);
useffect(()=>{
获取列表(调度);
}, []);
返回(
    {list.map((el)=>(
  • {el.title}
  • ))}
); };
reducer.ts

从“axios”导入axios;
常量列表成功='列表成功';
const LIST_FAILURE='LIST_FAILURE';
export const fetchList=async(dispatch)=>{
试一试{
const result=await axios.get('/list/');/*axios*/
分派({type:LIST_success,payload:result.data.LIST});
}捕获(错误){
分派({type:LIST_FAILURE});
}
};
导出常量listReducer=(状态、操作)=>{
开关(动作类型){
成功案例列表:
返回动作。有效载荷;
故障案例列表:
返回[];
违约:
抛出新错误();
}
};
index.spec.tsx

从“React”导入React;
从“/”导入{Posts};
从“酶”导入{mount};
从“axios”导入axios;
从'react dom/test utils'导入{act};
描述('Posts',()=>{
毕竟(()=>{
开玩笑。恢复记忆();
});
它('应该正确呈现列表',异步()=>{
constmresponse={data:{list:[{id:1,title:'jest'}]};
jest.spyOn(axios,'get').mockResolvedValueOnce(mResponse);
const wrapper=mount();
expect(wrapper.find('ul').children()).toHaveLength(0);
等待动作(异步()=>{
等待新承诺((resolve)=>setTimeout(resolve,0));
});
wrapper.update();
expect(wrapper.find('ul').children()).toHaveLength(1);
expect(包装器).toMatchInlineSnapshot(`
  • 开玩笑
`); }); 它('当请求列表数据失败时应呈现空列表',async()=>{ const mError=新错误(“内部服务器错误”); jest.spyOn(axios,'get').mockRejectedValueOnce(mError); const wrapper=mount(); expect(wrapper.find('ul').children()).toHaveLength(0); 等待动作(异步()=>{ 等待新承诺((resolve)=>setTimeout(resolve,0)); }); wrapper.update(); expect(wrapper.find('ul').children()).toHaveLength(0); expect(包装器).toMatchInlineSnapshot(`
    `); }); });
单元测试结果和覆盖率报告:

通过src/stackoverflow/59197574/index.spec.tsx(12.494s)
帖子
✓ 应正确呈现列表(105ms)
✓ 请求列表数据失败时应呈现空列表(37毫秒)
›写入1个快照。
------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
------------|----------|----------|----------|----------|-------------------|
所有文件| 95.83 | 66.67 | 100 | 95 ||
index.tsx | 100 | 100 | 100 | 100 ||
减速器ts | 92.86 | 66.67 | 100 | 91.67 | 21|
------------|----------|----------|----------|----------|-------------------|
快照摘要
›从1个测试套件中写入1个快照。
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:1个已写入,1个已通过,共2个
时间:14.409秒
源代码: