取消模拟模块时如何在Jest中模拟导入的命名函数 [英] How to mock imported named function in Jest when module is unmocked
问题描述
我要在Jest中测试以下模块:
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
}
如上所示,它导出一些命名函数,并且重要的是testFn
使用otherFn
.
As shown above, it exports some named functions and importantly testFn
uses otherFn
.
在Jest中,当我为testFn
编写单元测试时,我想模拟otherFn
函数,因为我不希望otherFn
中的错误影响我对testFn
的单元测试.我的问题是我不确定执行此操作的最佳方法:
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()
});
});
感谢您的帮助/见解.
推荐答案
在jest.mock()
内使用jest.requireActual()
jest.requireActual(moduleName)
返回实际模块而不是模拟模块,绕过所有有关该模块是否应接收模拟实施的检查.
jest.requireActual(moduleName)
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.
示例
在您需要并在返回的对象中散布的情况下,我更喜欢这种简洁的用法:
Example
I prefer this concise usage where you require and spread within the returned object:
// myModule.test.js
jest.mock('./myModule.js', () => (
{
...(jest.requireActual('./myModule.js')),
otherFn: () => {}
}
))
describe(...)
Jest的Manual Mocks文档中也引用了此方法(在 附近示例 ):
This method is also referenced in Jest's Manual Mocks documentation (near the end of Examples):
为确保手动模拟和它的实际实现保持同步,在导出之前,要求在手动模拟中使用
jest.requireActual(moduleName)
的真实模块并使用模拟功能对其进行修改可能会很有用.
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using
jest.requireActual(moduleName)
in your manual mock and amending it with mock functions before exporting it.
这篇关于取消模拟模块时如何在Jest中模拟导入的命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!