当前位置: 动力学知识库 > 问答 > 编程问答 >

unit testing - How to mock imported named function in Jest when module is unmocked

问题描述:

I have the following module I'm trying to test in Jest:

// myModule.js

export function otherFn() {

console.log('do something');

}

export function testFn() {

otherFn();

// do other things

}

As shown above, it exports some named functions and importantly testFn uses otherFn.

In Jest when I'm writing my unit test for testFn, I want to mock the otherFn function because I don't want errors in otherFn to affect my unit test for testFn. My issue is that I'm not sure the best way to do that:

// myModule.test.js

jest.unmock('myModule');

import { testFn, otherFn } from 'myModule';

describe('test category', () => {

it('tests something about testFn', () => {

// I want to mock "otherFn" here but can't reassign

// a.k.a. can't do otherFn = jest.fn()

});

});

Any help/insight is appreciated.

网友答案:

The transpiled code will not allow babel to retrieve the binding that otherFn() is referring to. If you use a function expession, you should be able to achieve mocking otherFn().

// myModule.js
exports.otherFn = () => {
  console.log('do something');
}

exports.testFn = () => {
  exports.otherFn();

  // do other things
}

 

// myModule.test.js
import m from '../myModule';

m.otherFn = jest.fn();

But as @kentcdodds mentioned in the previous comment, you probably would not want to mock otherFn(). Rather, just write a new spec for otherFn() and mock any necessary calls it is making.

So for example, if otherFn() is making an http request...

// myModule.js
exports.otherFn = () => {
  http.get('http://some-api.com', (res) => {
    // handle stuff
  });
};

Here, you would want to mock http.get and update your assertions based on your mocked implementations.

// myModule.test.js
jest.mock('http', () => ({
  get: jest.fn(() => {
    console.log('test');
  }),
}));
分享给朋友:
您可能感兴趣的文章:
随机阅读: