如何使用JEST和REACT解决axios模拟错误

时间:2019-10-12 18:09:16

标签: reactjs jestjs axios-mock-adapter

已经使用axios模拟方法创建了单元测试用例,并且确实看到了以下控制台错误。已经尝试了许多方法,但是都没有解决问题。对REACT / JEST社区来说是非常新的,但是要尽力解决。

期望:

  1. 所有测试用例,包括成功,错误场景,都应100%覆盖,并且应通过且没有警告/错误。
  2. 应使用空结果列表和非空结果列表来测试响应。
  3. 还应处理由于超时/网络引起的错误情况。

错误:


Expected: undefined
Received: {"results": []}

(node:76675) UnhandledPromiseRejectionWarning: 
Unhandled promise rejection. This error originated 
either by throwing inside of an async function without a catch block, 
or by rejecting a promise which was not handled with .catch(). 
(rejection id: 1)

(node:76675) [DEP0018] DeprecationWarning: Unhandled promise rejections 
are deprecated. In the future, promise rejections that are not handled will 
terminate the Node.js process with a non-zero exit code.

我尝试过的事情:

index.js

export default getAreas = area => axios.get(`/test/areas/${area}`);

__ mocks __ / axios.js

const axiosMocked = {
  get: jest.fn(() => Promise.resolve({ results: [] }))
};
export default axiosMocked;

__ tests __ / index.test.js

import mockAxios from 'axios';
import getAreas from '../index';

afterEach(() => {
  jest.clearAllMocks();
});

it('fetches results from api', () => {
  mockAxios.get.mockImplementationOnce(() => Promise.resolve({ results: [] }));
  getAreas('atl').then(response => {
    expect(response).toEqual();
  });
  expect(mockAxios.get).toHaveBeenCalledTimes(1);
  expect(mockAxios.get).toHaveBeenCalledWith('/test/areas/atl');
});

1 个答案:

答案 0 :(得分:0)

这是一种使用jest.mock方法手动模拟axios而不使用任何第三方模拟库的解决方案。

index.ts

import axios from 'axios';

const getAreas = area => axios.get(`/test/areas/${area}`);

export default getAreas;

index.spec.ts

import getAreas from './';
import axios from 'axios';

jest.mock('axios');

afterEach(() => {
  jest.clearAllMocks();
});

describe('getAreas', () => {
  it('fetches results from api', () => {
    (axios.get as jest.Mock).mockResolvedValueOnce({ results: [] });
    getAreas('atl').then(response => {
      expect(response).toEqual({ results: [] });
    });
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('/test/areas/atl');
  });
});

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

 PASS  src/stackoverflow/58357043/index.spec.ts (7.557s)
  getAreas
    ✓ fetches results from api (9ms)

----------|----------|----------|----------|----------|-------------------|
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:       1 passed, 1 total
Snapshots:   0 total
Time:        8.952s

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