为了账号安全,请及时绑定邮箱和手机立即绑定

如何在玩笑中正确使用 axios.get.mockResolvedValue 进行异步调用

如何在玩笑中正确使用 axios.get.mockResolvedValue 进行异步调用

慕田峪4524236 2021-11-12 14:21:25
我想用 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 {}我希望测试应该通过,因为我在嘲笑一个被拒绝的值。
查看完整描述

1 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

您可以创建一个模拟函数来替换axios.get()方法。


index.ts:


import axios from 'axios';


export async function getUserDataByIds(ids: string[]) {

  try {

    const users = await axios.get('/users');

    return users;

  } catch (err) {

    return new Map();

  }

}

index.spec.ts:


import { getUserDataByIds } from './';

import axios from 'axios';


describe('getUserDataByIds', () => {

  it('should return empty Map when axios.get failed', async () => {

    const getError = new Error('network error');

    axios.get = jest.fn().mockRejectedValue(getError);

    const actualValue = await getUserDataByIds(['1']);

    expect(actualValue).toEqual(new Map());

    expect(axios.get).toBeCalledWith('/users');

  });


  it('should return users', async () => {

    const mockedUsers = [{ userId: 1 }];

    axios.get = jest.fn().mockResolvedValue(mockedUsers);

    const actualValue = await getUserDataByIds(['1']);

    expect(actualValue).toEqual(mockedUsers);

    expect(axios.get).toBeCalledWith('/users');

  });

});

100% 覆盖率的单元测试结果:


 PASS  src/stackoverflow/58273544/index.spec.ts

  getUserDataByIds

    ✓ should return empty Map when axios.get failed (12ms)

    ✓ should return users (4ms)


----------|----------|----------|----------|----------|-------------------|

File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |

----------|----------|----------|----------|----------|-------------------|

All files |      100 |      100 |      100 |      100 |                   |

 index.ts |      100 |      100 |      100 |      100 |                   |

----------|----------|----------|----------|----------|-------------------|

Test Suites: 1 passed, 1 total

Tests:       2 passed, 2 total

Snapshots:   0 total

Time:        5.597s, estimated 7s

源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58273544


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 348 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信