javascript SpyOn一个导出类Jasmine的导入模块

xpcnnkqh  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(171)

请检查下面的测试文件注解以了解问题

//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()返回假对象?
简而言之,如何模拟一个依赖项,这个依赖项被用作模块导出的类。

qeeaahzv

qeeaahzv1#

//myModule-test.js

import proxyquire from 'proxyquire';

import MyModule from '../myModule';
import Dependency from '../dependency';

const mockedDependencyInstance = {
    doSomething: () => {}
};

const mockedDependencyConstructor = () => {
     return mockedDependencyInstance;
};

describe('MyModule', () => {
  it('doSomething on the dependency called on init', () => {
    proxyquire('../myModule.js', {
        '../dependency.js': mockedDependencyConstructor
    });
    
    //Using proxyquire solves above issue and it allows to mock dependencies

    const myModule_ = new MyModule();

    myModule_.init();

    expect(mockedDependencyConstructor.doSomething).toHaveBeenCalled();
  });
});

proxyquire
As explained here
另一个问题是proxyquire不支持webpack。
所以,如果你使用webpack〈= 4,试试inject-loader,不幸的是,webpack 5不支持注入加载器.
如果您使用的是webpack5,请尝试使用rewiremock,您可能很幸运地没有遇到here问题

相关问题