简体   繁体   English

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

[英]How to resolve axios mocking errors using JEST and REACT

Have created unit test cases using axios mock approach and do see below console errors.已经使用 axios 模拟方法创建了单元测试用例,并看到下面的控制台错误。 Have tried many approaches but none resolved the problem.尝试了很多方法,但都没有解决问题。 Very new to REACT/JEST community, but trying best to resolve this.对 REACT/JEST 社区来说非常新,但会尽力解决这个问题。

Expectation:期待:

  1. All test cases including success, error scenarios should be 100% covered and should pass with no warnings/errors.包括成功、错误场景在内的所有测试用例都应 100% 覆盖,并且应在没有警告/错误的情况下通过。
  2. Response should be tested with empty results list and as well with non-empty results list.应使用空结果列表和非空结果列表测试响应。
  3. Error scenarios due to timeout/network should also be handled.还应处理由于超时/网络引起的错误场景。

Errors:错误:


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.

What I tried:我尝试了什么:

index.js index.js

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

__mocks__/axios.js __mocks__/axios.js

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

__tests__/index.test.js __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');
});

Here is a solution using jest.mock method to mock axios manually without using any third-party mock library.这是使用jest.mock方法手动模拟axios而不使用任何第三方模拟库的解决方案。

index.ts : index.ts

import axios from 'axios';

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

export default getAreas;

index.spec.ts : 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');
  });
});

Unit test result with 100% coverage:覆盖率 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM