Lately I’ve been looking for a good mocking library for node.js. It’s not easy.
Here are some (I would have said obvious) features that seem to be missing in most of the libraries I’ve seen:
- create an anonymous mock object on which to add expected methods (no need to provide a template object)
- create a (named) mock function (i.e a directly callable mock)
- argument matchers (at least eq(), given how terrible javascript equality is)
- stub a single method of a real object for the duration of the test
- verify all expectations and revert all replaced methods (see #4) with a single call (to be called from a common tearDown())
I don’t want it to be tied to my test runner, I’m quite happy with mocha.
I prefer the rspec style of setting expectations on mocks before the code is run and having them verified at the end of the test, but it’s not a requirement.
I plan need it to run in node.js, but would like it to work in the browser (even if I have to use some sort of commonJS-shim).
Here are the libraries I tried to use or looked at, and reasons they will not suffice:
- sinon.js: fails 1, 2, 3, 4, 5, although it comes close to 2 and 3
- node-gently: fails 2, 3, 5
- mimic: fails 1, 2, 3, 4
- MaryJane: fails all of the above
- espionage: fails all of the above
Honestly, I looked at most of the unit testing modules listed on the node.js wiki that sounded like they did mocking.
jasmine’s mocking support seems somewhat reasonable (I’ve used it before), but unfortunately it seems to be tied to the jasmine test runner, which is not acceptable for async tests.
I’m happy to be shown wrong about my conclusions here, or to be pointed to any mocking library that succeeds in most (or at least more) of my requirements. If all else fails I may consider porting my mocktest python library to javascript as best as the language will allow, but it’s probably a lot of effort - surely someone has written a good javascript mocking library somewhere amongst all this? What do other folks use?