Sarbbottam
Sarbbottam

Reputation: 5580

Mocking dependency in Node (mainly for unit testing)

Searched for a while before raising the question.

File structure:

.
|____lib
| |____bar.js
| |____baz.js
| |____foo.js
|____test
| |____bar.js
| |____baz.js
| |____foo.js

Use case:

With respect to the above file structure, ./lib/foo.js requires ./lib/bar.js, ./lib/bar.js requires ./lib/baz.js.


While unit testing ./lib/foo.js via ./test/foo.js, I would like to mock ./lib/bar.js, so that, I am only concerned with ./lib/foo.js. Once the tests in ./test/foo.js are over I would like to reset/un-mock ./lib/bar.js.

While unit testing ./lib/bar.js via ./test/bar.js, I would like to mock ./lib/baz.js, so that, I am only concerned with ./lib/baz.js. Once the tests in ./test/foo.js are over I would like to reset/un-mock ./lib/baz.js.

So on and so forth.


Or in other words, I would like to mock the dependencies and reset as and when required, in the test file.

Most likely mocking several times in the test file and reseting a after all the test are over in a test file.

Or may be I can control the local mock, with some file level closure variables


Below mentioned StackOverflow posts have excellent discussion but I could not come to any conclusion.

I came across the following modules

and few others.


Among the above, looks like mockery addresses my use-case, mainly reset/un-mock the mocked dependency.

How to achieve the same in proxyquire?


Is there any other module which addresses the stated use case?

Upvotes: 3

Views: 795

Answers (1)

jamlen
jamlen

Reputation: 198

I use a combination of deride and rewire.

For example to test foo.js I will:

var rewire = require('rewire');
var deride = require('deride');
var Foo = rewire('../lib/foo');
var mockBar, foo;

describe('something', function() {
  beforeEach(function() {
      mockBar = deride.stub(['barMethod']);
      mockBar.setup.barMethod.when('bob').toReturn('Hello bob');
      Foo.__set__('bar', mockBar);
      foo = new Foo();
  });

  it('does something', function() {
    foo.someMethod('bob');
    mockBar.expect.barMethod.called.withArgs(['bob']);
  });
});

And there is no unsetting required.

DISCLAIMER: I am one of the authors of deride :)

Upvotes: 2

Related Questions