假设在我的 util.js 中我有
export function foo(){ ... do something}
export function bar(){ ... do something}
...
在各种组件中我使用 foo
//Foo1.component.js
import { foo } from './util'A
... do something using foo.
//Foo2.component.js
import { foo } from './util'A
... do something using foo.
等等..
我该如何模拟这个,例如在 Foo1.test.js
中。
更好的是,有没有办法让我可以从 jest.config 中“劫持”这个 foo
导入。
也许在 moduleNameMapper
中?
所以它已经被所有测试 Foo1.test.js
和 Foo2.test.js
模拟了?
最佳答案
是的,有一种方法可以在测试环境中模拟模块。
如果您想模拟特定测试文件中的模块,您可以尝试使用 jest.mock()
函数。例如,模拟 Foo1.component.js
测试文件中的 foo
方法将如下所示:
// Foo1.component.test.js
jest.mock('./path/to/utils.js', () => ({
foo: () => { // custom implementation for test env }
bar: () => { // custom implementation for test env if needed }
}));
// The foo imported below has the custom implementation for test env
import { foo } from './util';
另一个选择是创建一个模拟模块,我认为这更适合您的需求。在utils.js
所在文件夹中,创建一个__mocks__
文件夹,在该文件夹下添加一个文件utils.js
(同名)作为要模拟的模块),在该文件中,您可以为 util.js 模块编写模拟行为。例如:
// __mocks__/utils.js
export function foo(){ ... mock implementation}
export function bar(){ ... mock implementation}
每当您的测试文件中需要这些模拟实现时,只需使用模块的路径调用 jest.mock
方法即可。例如:
// Foo1.component.test.js
jest.mock('./path/to/utils.js');
// The foo imported below has the custom implementation for test env
import { foo } from './util';
链接:
关于javascript - 如何使用 jest 全局模拟单个实用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293085/