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.

kekko12
  • 566
  • 1
  • 6
  • 19

1 Answers1

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);
Lennholm
  • 7,205
  • 1
  • 21
  • 30
  • The problem is that in my tests, I cannot get access to the `client` instance, therefore i cannot spy on any of the methods. – kekko12 Jul 07 '17 at 13:56
  • 1
    @kekko12 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. – Lennholm Jul 07 '17 at 13:58
  • 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. – kekko12 Jul 07 '17 at 21:08
  • proxyquire is the way to go – user566245 Jun 24 '19 at 20:43