vendredi 20 février 2015

Sinon - when to use spies/mocks/stubs or just plain assertions?

I'm trying to understand how Sinon is used properly in a node project. I have gone through examples, and the docs, but I'm still not getting it. I have setup a directory with the following structure to try and work through the various Sinon features and understand where they fit in



|--lib
|--index.js
|--test
|--test.js


index.js is



var myFuncs = {};

myFuncs.func1 = function () {
myFuncs.func2();
return 200;
};

myFuncs.func2 = function(data) {
};

module.exports = myFuncs;


test.js begins with the following



var assert = require('assert');
var sinon = require('sinon');
var myFuncs = require('../lib/index.js');

var spyFunc1 = sinon.spy(myFuncs.func1);
var spyFunc2 = sinon.spy(myFuncs.func2);


Admittedly this is very contrived, but as it stands I would want to test that any call to func1 causes func2 to be called, so I'd use



describe('Function 2', function(){
it('should be called by Function 1', function(){
myFuncs.func1();
assert(spyFunc2.calledOnce);
});
});


I would also want to test that func1 will return 200 so I could use



describe('Function 1', function(){
it('should return 200', function(){
assert.equal(myFuncs.func1(), 200);
});
});


but I have also seen examples where stubs are used in this sort of instance, such as



describe('Function 1', function(){
it('should return 200', function(){
var test = sinon.stub().returns(200);
assert.equal(myFuncs.func1(test), 200);
});
});


How are these different? What does the stub give that a simple assertion test doesn't?


What I am having the most trouble getting my head around is how these simple testing approaches would evolve once my program gets more complex. Say I start using mysql and add a new function



myFuncs.func3 = function(data, callback) {
connection.query('SELECT name FROM users WHERE name IN (?)', [data], function(err, rows) {
if (err) throw err;
names = _.pluck(rows, 'name');
return callback(null, names);
});
};


I know when it comes to databases some advise having a test db for this purpose, but my end-goal might be a db with many tables, and it could be messy to duplicate this for testing. I have seen references to mocking a db with sinon, and tried following this answer but I can't figure out what's the best approach.


Aucun commentaire:

Enregistrer un commentaire