Jest - dontMock function not working as expected

1k Views Asked by At

Im trying to unmock axios module inside the test function, but it keeps returning the mocked response even tho i have declared the dontMock function. What am i doing wrong?

   import Axios from 'axios';   

   jest.mock('axios');

   describe('Testing Async Selectors', () => 
        it('should render empty dropdown', async () => {

           console.log(Axios);
        });

        it('should render empty dropdown', async () => {
           jest.dontMock('axios');

           console.log(Axios);
        });

  });
1

There are 1 best solutions below

0
Lin Du On BEST ANSWER

jest.dontMock(moduleName) should be used with jest.doMock(moduleName, factory, options).

E.g.

describe('Testing Async Selectors', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('should mock axios', async () => {
    jest.doMock('axios');
    const Axios = require('axios');
    expect(jest.isMockFunction(Axios)).toBeTruthy();
  });

  it('should not mock axios', async () => {
    jest.dontMock('axios');
    const Axios = require('axios');
    expect(jest.isMockFunction(Axios)).toBeFalsy();
  });
});

unit test result:

 PASS  src/stackoverflow/64818492/index.test.ts (9.71s)
  Testing Async Selectors
    ✓ should mock axios (47ms)
    ✓ should not mock axios (4ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.762s