How to mock a module that is required in another module with Jasmine
Asked Answered
S

1

6
const Client = require('./src/http/client');

module.exports.handler = () => {
    const client = new Client();
    const locationId = client.getLocationId(123);
};

How can I test this module asserting that the client.getLocationId has been called with the 123 argument in Jasmine?

I know how to achieve that with Sinon, but I have no clue about Jasmine.

Sunwise answered 7/7, 2017 at 13:3 Comment(0)
A
5

Where with Sinon you would do:

Sinon.spy(client, 'getLocationId');

...

Sinon.assert.calledWith(client.getLocationId, 123);

with Jasmine you do:

spyOn(client, 'getLocationId');

...

expect(client.getLocationId).toHaveBeenCalledWith(123);

Update: So, what you need is to mock the Client module when it's required by the module you're testing. I suggest using Proxyquire for this:

const proxyquire = require('proxyquire');
const mockedClientInstance = {
  getLocationId: () => {}
};
const mockedClientConstructor = function() {
  return mockedClientInstance;
};

const moduleToTest = proxyquire('moduleToTest.js', {
  './src/http/client': mockedClientConstructor
});

This will inject your mock as a dependency so that when the module you're testing requires ./src/http/client, it will get your mock instead of the real Client module. After this you just spy on the method in mockedClientInstance as normal:

spyOn(mockedClientInstance, 'getLocationId');
moduleToTest.handler();
expect(mockedClientInstance.getLocationId).toHaveBeenCalledWith(123);
Abeu answered 7/7, 2017 at 13:50 Comment(4)
The problem is that in my tests, I cannot get access to the client instance, therefore i cannot spy on any of the methods.Sunwise
@Sunwise Well that shouldn't make any difference between Sinon and Jasmine. You mentioned that you know how to achieve it with Sinon. How would you do that? Any solution for that should work fine with Jasmine.Abeu
Actually I thought I knew, but I just tried and that is not working. It works only if the required module is a instance (singleton). I guess that the only option is to use Proxyquire.Sunwise
proxyquire is the way to goGiarla

© 2022 - 2024 — McMap. All rights reserved.