我已经能够通过使用涉及到的hack来解决此问题
import *。它甚至适用于命名和默认导出!
对于命名出口:
// dependency.jsexport const doSomething = (y) => console.log(y)// myModule.jsimport { doSomething } from './dependency';export default (x) => { doSomething(x * 2);}// myModule-test.jsimport myModule from '../myModule';import * as dependency from '../dependency';describe('myModule', () => { it('calls the dependency with double the input', () => { dependency.doSomething = jest.fn(); // Mutate the named export myModule(2); expect(dependency.doSomething).toBeCalledWith(4); });});
或默认导出:
// dependency.jsexport default (y) => console.log(y)// myModule.jsimport dependency from './dependency'; // Note lack of curliesexport default (x) => { dependency(x * 2);}// myModule-test.jsimport myModule from '../myModule';import * as dependency from '../dependency';describe('myModule', () => { it('calls the dependency with double the input', () => { dependency.default = jest.fn(); // Mutate the default export myModule(2); expect(dependency.default).toBeCalledWith(4); // Assert against the default });});
正如Mihai
Damian在下面正确指出的那样,这是对的模块对象进行了变异
dependency,因此它将“泄漏”到其他测试中。因此,如果使用这种方法,则应存储原始值,然后在每次测试后再次将其重新设置。要使用Jest轻松实现此目的,请使用spyOn()方法代替,
jest.fn()因为它支持轻松恢复其原始值,因此避免了前面提到的“泄漏”。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)