0

Please check the test file comment below for the issue

//dependency.js

const function Dependency(property) {
    this.property = property;
}

Dependency.prototype.doSomething = function () {
    console.log('inside doSomething property: ', this.property);
}

export default Dependency;

Another File

//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;

Test File

//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();
  });
});

How to make Dependency Spy so that new Dependency() inside the MyModule.js returns the fake object?

In short, how to mock a dependency which is used as a class exported by a module.

3960278
  • 756
  • 4
  • 12

1 Answers1

0
//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

Another issue is webpack is not supported by proxyquire.

So, If you are using webpack <= 4 try inject-loader, Unfortunately, webpack 5 isn't supported by inject-loader.

If you are using webpack 5, try using rewiremock, you might be fortunate enough to not stuck here

3960278
  • 756
  • 4
  • 12