【问题标题】:can I mock an imported function in jest unit我可以在笑话单元中模拟导入的函数吗
【发布时间】:2020-07-30 05:32:44
【问题描述】:

我有这样的代码

import fun from '../../../example';
export async function init (props:any){
   if (fun()){
      doSomething();
   }
}

我正在为上面的这段代码创建单元测试,但实际上我只想在文件中模拟 fun 的实现,因为我无法更改原始文件中的 fun

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    您可以使用jest.mock(moduleName, factory, options) 模拟../../../example 模块。

    例如

    index.ts:

    import fun from './example';
    
    export async function init(props: any) {
      if (fun()) {
        console.log('doSomething');
      }
    }
    

    example.ts:

    export default function fun() {
      console.log('real implementation');
      return false;
    }
    

    index.test.ts:

    import { init } from './';
    import fun from './example';
    import { mocked } from 'ts-jest/utils';
    
    jest.mock('./example', () => jest.fn());
    
    describe('63166775', () => {
      it('should pass', async () => {
        expect(jest.isMockFunction(fun)).toBeTruthy();
        const logSpy = jest.spyOn(console, 'log');
        mocked(fun).mockReturnValueOnce(true);
        await init({});
        expect(logSpy).toBeCalledWith('doSomething');
        expect(fun).toBeCalledTimes(1);
        logSpy.mockRestore();
      });
    });
    

    单元测试结果:

     PASS  stackoverflow/63166775/index.test.ts (13.298s)
      63166775
        ✓ should pass (33ms)
    
      console.log
        doSomething
    
          at CustomConsole.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |       50 |     100 |     100 |                   
     index.ts |     100 |       50 |     100 |     100 | 4                 
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        15.261s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2021-09-19
      相关资源
      最近更新 更多