mockery icon indicating copy to clipboard operation
mockery copied to clipboard

How to Spy On a Mocked Thing?

Open JimLynchCodes opened this issue 4 years ago • 2 comments

Hello! Thanks for making this nice module! I'm wondering how I can "spy on" a mocked module so that I can make assertions about how it was called.

Suppose I am trying to mock the request-promise libary which is normally called with request.get, here's my mockery code:

mockery.registerMock('request-promise', {
      get: () => {
        return {
          statusCode: 200,
          body: {
            foo: "barracuda"
          },
        };
      },
    });

    mockery.enable({
      warnOnReplace: false,
      warnOnUnregistered: false,
    });

I would like to assert that request.get was called with the correct params. I tried setting up a sinon spy as usual, it didn't seem to work. :/

requestSpy = sinon.spy(request, 'get')

Is there any recommended way to do this with mockery?

Thanks! 🙏

JimLynchCodes avatar Jan 23 '20 05:01 JimLynchCodes

Um... yeah I don't think you can do that with this lib. Anyone else can prove me wrong, please do. Try using this library: https://www.npmjs.com/package/proxyquire

const myStub = sinon.stub();

const mut = proxyquire('../src/myFile.js', {
   'fs': myStub,
});

myStub.returns(5);

const results = mut.testFunction();

sinon.assert.callCount(myStub, 1);
sinon.assert.calledWith(myStub, 'some_thing');

That's how I've always done it.

jackmead515 avatar May 02 '20 03:05 jackmead515

Do sinon stuff after require, e.g. see https://github.com/mawie81/electron-window-state/blob/master/test.js#L37 So, for your case

const request = require('request-promise');
requestSpy = sinon.spy(request, 'get');

xmedeko avatar May 27 '21 19:05 xmedeko