Javascript 如何正确使用axios.get.mockResolvedValue进行异步调用

Javascript 如何正确使用axios.get.mockResolvedValue进行异步调用,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我想用Jest模拟异步函数的catch块中的返回值 这就是我正在编写单元测试的函数: try { make some axios request } return users; } catch (err) { return new Map(); } }; it('should catch error when query is unsuccessful', async () => { axios.get.mockReject

我想用Jest模拟异步函数的catch块中的返回值

这就是我正在编写单元测试的函数:

  try {
    make some axios request
    }
    return users;
  } catch (err) {
    return new Map();
  }
};

    it('should catch error when query is unsuccessful', async () => {
      axios.get.mockRejectedValue(new Map());
      const res = getUserDataByIds('someUserIds');
      await expect(res).rejects.toThrow();
    });

我从Jest那里得到了错误:

 expect(received).rejects.toEqual()
 Received promise resolved instead of rejected
 Resolved to value: Map {}
我希望测试应该通过,因为我正在模拟一个被拒绝的值。

以下是解决方案:

index.ts

从“axios”导入axios;
导出异步函数GetUserDataByDS(ID:string[]){
试一试{
const users=wait axios.get('/users');
返回用户;
}捕捉(错误){
返回新映射();
}
}
索引规范ts

从“/”导入{getUserDataByIds};
从“axios”导入axios;
开玩笑的模仿(‘axios’);
描述('GetUserDataByDS',()=>{
之后(()=>{
jest.resetAllMocks();
});
它('当axios.get失败时应返回空映射',async()=>{
const getError=新错误(“网络错误”);
axios.get=jest.fn().mockRejectedValue(getError);
const actualValue=await getUserDataById(['1']);
expect(实际值).toEqual(新映射());
expect(axios.get).toBeCalledWith('/users');
});
它('should return users',async()=>{
const mockedUsers=[{userId:1}];
axios.get=jest.fn().mockResolvedValue(mockedUsers);
const actualValue=await getUserDataById(['1']);
expect(实际值)、toEqual(模拟用户);
expect(axios.get).toBeCalledWith('/users');
});
});
100%覆盖率的单元测试结果:

PASS src/stackoverflow/58273544/index.spec.ts
GetUserDataByds
✓ axios.get失败时应返回空映射(12毫秒)
✓ 应返回用户(4ms)
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:5.597秒,估计7秒
源代码: