请检查下面的测试文件注解以了解问题
//dependency.js
const function Dependency(property) {
this.property = property;
}
Dependency.prototype.doSomething = function () {
console.log('inside doSomething property: ', this.property);
}
export default Dependency;
其他文件
//myModule.js
import Dependency from './Dependency.js';
const function MyModule () {
this.dependency = new Dependency('Some Property');
}
MyModule.protoype.init = function () {
this.dependency.doSomething();
}
export default MyModule;
测试文件
//myModule-test.js
import MyModule from '../myModule';
import Dependency from '../dependency';
describe('MyModule', () => {
it('doSomething on the dependency called on init', () => {
//Here is the problem, How to make Dependency Spy so that new Dependency()
//inside the MyModule.js returns the fake object
//Right now there are two instances one in the next line and another in MyModule.js
const $DependencyFake = new Dependency('Testing');
// spyOn(Dependency, 'doSomething');
const myModule_ = new MyModule();
myModule_.init();
expect($DependencyFake.doSomething).toHaveBeenCalled();
});
});
如何使Dependency Spy使MyModule.js中的新Dependency()返回假对象?
简而言之,如何模拟一个依赖项,这个依赖项被用作模块导出的类。
1条答案
按热度按时间qeeaahzv1#
proxyquire
As explained here
另一个问题是proxyquire不支持webpack。
所以,如果你使用webpack〈= 4,试试inject-loader,不幸的是,webpack 5不支持注入加载器.
如果您使用的是webpack5,请尝试使用rewiremock,您可能很幸运地没有遇到here问题