【问题标题】:How to test jest mock module如何测试 jest mock 模块
【发布时间】:2020-02-12 15:58:09
【问题描述】:
// utils.js
var someModule = require('someModule');

someModule.setKey('API_KEY');

我想测试setKey 功能。所以我写了下面的单元测试用例。

jest.mock('someModule, () => {
   return {
     setKey: jest.fn()
   }
})

describe('utils', () => {
   afterEach(()=> {
      jest.clearAllMocks()
   })

   it(`test case 1`, () => {})

   it(`test case utils`, () => {
       expect(someModule.setKey.mocks.calls).toHaveLength(1)
   })
});

最后一个测试用例失败,但如果我将最后一个测试用例移到第一个,那么它就可以工作。由于没有执行clearAllMocks 函数。

什么应该是测试它的好方法?

【问题讨论】:

    标签: javascript node.js reactjs unit-testing jestjs


    【解决方案1】:

    它应该工作。这是一个例子:

    utils.js:

    const someModule = require('someModule');
    
    function main() {
      someModule.setKey('API_KEY');
    }
    
    module.exports = main;
    

    由于someModule 不是真正的模块,所以我使用{virtual: true} 选项。

    utils.test.js:

    const main = require('./utils');
    const someModule = require('someModule');
    
    jest.mock(
      'someModule',
      () => {
        return { setKey: jest.fn() };
      },
      { virtual: true },
    );
    
    describe('60192332', () => {
      afterEach(() => {
        jest.clearAllMocks();
      });
      it('should set key', () => {
        main();
        expect(someModule.setKey.mock.calls).toHaveLength(1);
      });
    });
    

    100% 覆盖率的单元测试结果:

     PASS  stackoverflow/60192332/utils.test.js (6.732s)
      60192332
        ✓ should set key (5ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     utils.js |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        8.38s, estimated 13s
    

    【讨论】:

    • 感谢您的输入,但在您的代码中,someModule.setKey 函数已移至 main 函数。但我希望它像我在代码中显示的那样加载一次
    猜你喜欢
    • 2017-07-15
    • 2021-10-11
    • 2018-09-16
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 2018-09-14
    • 2018-08-27
    • 2022-08-18
    相关资源
    最近更新 更多