mockery icon indicating copy to clipboard operation
mockery copied to clipboard

How to verify whether a call to require actually happened?

Open goloroden opened this issue 11 years ago • 3 comments

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?

goloroden avatar Dec 19 '13 10:12 goloroden

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);
});

neverfox avatar Jan 09 '15 05:01 neverfox

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.

krohrsb avatar Oct 12 '15 18:10 krohrsb

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"));

cspotcode avatar Dec 13 '15 04:12 cspotcode