最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock a module that is required in another module with Jasmine - Stack Overflow

programmeradmin5浏览0评论
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.

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.

Share Improve this question asked Jul 7, 2017 at 13:03 kekko12kekko12 5761 gold badge6 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论