mockery
mockery copied to clipboard
How to verify whether a call to require actually happened?
I am using mockery to mock some modules. Now I have a special case where I just want to know whether a call to require
with a specific module happened or not. As this has no side-effects that are visible from the outside, I can not test any specific behavior.
Basically I just need to know if require
was called with parameter foo
or not.
How could I test this?
Wouldn't Sinon make this possible?
it("requires `foo`", function () {
var moduleSpy = sinon.spy();
mockery.registerMock('foo', moduleSpy);
// do whatever should cause `require('foo')`
assert(moduleSpy.called);
});
Simply requiring a mocked module doesn't execute the spy. It returns the spy. So in this case, called would still be false
.
It would be neat to have the ability to ask mockery if a mocked module was required.
It wouldn't be too hard for mockery to implement Node's EventEmitter
and fire an event every time _load
receives a request.
var requireSpy = sinon.spy();
mockery.on('require', requireSpy);
/* do some test code */
// Assert that the "some-module" was required
requireSpy.calledWith(require.resolve("some-module"));