0

Have created unit test cases using axios mock approach and do see below console errors. Have tried many approaches but none resolved the problem. Very new to REACT/JEST community, but trying best to resolve this.

Expectation:

  1. All test cases including success, error scenarios should be 100% covered and should pass with no warnings/errors.
  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

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');
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
user12133234
  • 371
  • 2
  • 5
  • 15
  • what is path to `__mocks__/axios.js`? it [should be](https://jestjs.io/docs/en/manual-mocks#mocking-node-modules) adjacent to node_modules (unless you configured roots to point to a folder other than the project root). also I see `axios-mock-adapter` among tags but your test does not use it. believe me, it's easier to use it instead of mocking `axios` manually each time – skyboyer Oct 12 '19 at 18:33
  • @skyboyer - yes it is adjacent to node_modules. I tried with axios-mock-adapter, but that as well failed. Can you pls provide some sample related to my code – user12133234 Oct 12 '19 at 18:52

1 Answers1

-1

Here is a solution using jest.mock method to mock axios manually without using any third-party mock library.

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');
  });
});

Unit test result with 100% coverage:

 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

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • This answer does not address the original concern which is how to mock axios error. A much better and generic answer would suggest mock implementation of the axios method error scenarios – Deepak May 08 '21 at 13:03