mockery
mockery copied to clipboard
How to Spy On a Mocked Thing?
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! 🙏
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.
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');