I've created a database wrapper for my application, shown below. To test it, I obviously would like to replace the actual database library. I could create a new class that mocks the query
method and catch all input there, but using sinon.js
seems more appropriate, but how would I use it?
Is the mock
or stub
features of sinon.js
what I should be using?
wrapper = (function() {
function wrapper() {}
wrapper.db = require("database");
wrapper.prototype.insertUser = function(doc) {
return this.db.query("INSERT INTO USERS...");
};
return wrapper;
})();
You can use both for that.
Mock have an expected ordered behavior that, if not followed correctly, is going to give you an error.
A Stub is a similar to a mock, but without the order, so you can call your methods the way you want. In my experience you almost never need a mock.
Both of them will substitute your method for an empty method, or a closure if you pass one. It would be something like this:
stub = sinon.stub(wrapper , 'insertUser ', function () { return true; });
Then you add the expect behavior to check if it did happened.
I like to use Jasmine with Jasmine-Sinon for checking the tests.
This doesn't quite answer the question IMHO
If you want to check if the function insertUser is making the correct call internally then this doesn't verify it.
A mock here is checking the calls are correct and mocking out the db.query call with an expectation does this without having to hit the database.
As I'm fairly new to JavaScript, I'm trying to work out the best way to setup the db mock with sinon.
In .Net land I would ask the mocking tool to create me a mock and I'd pass that in using a constructor on a class. You would need a hell good mocking tool to mock out third party components in the .Net environment environment. So many people use the open source tools which forces them to create another abstraction to limit the surface area of the code they can't mock.
In JavaScript I suspect it would be easier. Interested to hear of anyone else's thoughts on this and potential solutions.