【问题标题】:Jest - dontMock function not working as expected开玩笑 - dontMock 功能没有按预期工作
【发布时间】:2021-02-25 07:38:37
【问题描述】:

我试图在测试函数中取消模拟 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);
        });

  });

【问题讨论】:

    标签: javascript axios jestjs mocking jest-mock-axios


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 2021-08-18
      • 1970-01-01
      • 2021-12-26
      • 2018-08-17
      • 2021-10-16
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多