Unit Test - makingsensetraining/mean-seed-blog GitHub Wiki
We are going to provide some little examples for creating Unit Test for the Controllers and Services layer
- For testing Controllers we will fake or apply the stub (using sinon) that you could check on the separated wiki page.
Example:
var posts = {
"_id": "5ecc7850-4ac5-11e6-958e-edc6f4d97e24",
"title": "TestTitle",
"__v": 0,
"text": "TestText"
};
describe('#getPosts', function() {
var serviceGetPostStub;
before(function () {
serviceGetPostStub = sinonSandbox.stub(blogService, 'getPosts');
});
it('shout retrieve the posts and return the expected response', function (done) {
serviceGetPostStub.callsArgWith(0, null, { post: posts });
// Call to the controller method
blogController.getPosts({
body:{}
},{
send: function(ret){
ret.should.eql({
post: posts
});
done();
}
});
});
Above, we are replacing with stub the getPosts function of blogService. So we are returning one fixed object that you see in the post variable.
So inside the test with ret.should.eql() function we wait that the result is the same as the post variable, and so we are testing the controller functionality, separating or decoupling the service layer.
- For testing Services we will fake or apply the stub again.
Example:
before(function () {
findByIdStub = sinonSandbox.stub(blogModel, 'findOne');
});
it('should find a post if it already exists', function (done) {
var idPost = '5ecc7850-4ac5-11e6-958e-edc6f4d97e2';
findByIdStub.callsArgWith(1, null, {
_id: idPost
});
blogService.show({
params: {
id: '5ecc7850-4ac5-11e6-958e-edc6f4d97e24'
}
}, function (err, response) {
response._id.should.eql(idPost);
done();
});
});
In the above example we see that with the findByIdStub we are replacing the findOne method of the blogModel (that is not more than an associated mongoose schema/mapping)
In fact, we need to decouple the model layer, to test the service one, that's why we replace the model method.
After that inside the blogService.show() method we check the response, that have to be the same as the expected (a fixed id).