0

我试图在测试函数中取消模拟 axios 模块,但即使我已经声明了 dontMock 函数,它也会继续返回模拟的响应。我究竟做错了什么?

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

  });
4

1 回答 1

1

jest.dontMock(moduleName)应该与jest.doMock(moduleName, factory, options)一起使用。

例如

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

单元测试结果:

 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
于 2020-11-14T03:13:34.260 回答