lundi 4 mai 2015

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 to 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?

Aucun commentaire:

Enregistrer un commentaire