简体   繁体   中英

can I mock an imported function in jest unit

I have a code like this

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

I'm creating unit tests for this code above, but I actually want to mock the implementation of fun in the file only as I can't alter fun in its original file

You can use jest.mock(moduleName, factory, options) to mock ../../../example module.

Eg

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

unit test result:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM