3 回答
TA贡献1804条经验 获得超2个赞
我已经能够通过使用涉及到的黑客解决此问题import *。它甚至适用于命名和默认导出!
对于命名出口:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import 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.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import 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()因为它支持轻松恢复其原始值,因此避免了前面提到的“泄漏”。
TA贡献1842条经验 获得超12个赞
您必须模拟模块并自己设置间谍:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
doSomething: jest.fn()
}))
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
添加回答
举报