
//data.js var fs = require('fs'); module.exports = { todos : { get: function() { var data = fs.readFileSync('./todos.json', 'utf-8'); return JSON.parse(data); }, save: function(todo) { var data = fs.readFileSync('./todos.json', 'utf-8'); var todos = JSON.parse(data); todos.push(todo); fs.writeFileSync('./todos.json', JSON.stringify(todos)); } } }
Next we will write a test case using mocha. We have to create a test folder inside our application and then we have created test.js file to write the test cases. In the below test we have used describe function which is used to set up a group of test with a name (in our case it is dataTest). Then we have a it function which is given a description of what the test is doing and then the second argument will contain the assertions using should.js.
var should = require('should'); describe('dataTest', function() { var data = require('../data.js'); it('todo count should increase by 1', function () { var todos = data.todos.get(); data.todos.save({todoName : 'Write Coding Defined 1st Post'}); var latestTodos = data.todos.get(); latestTodos.length.should.equal(todos.length + 1); }); });
After that you should run mocha in the command prompt which will by default run everything in /test folder. After running you will see the result as shown below :
In this post we have looked at a practical example of unit testing in Node using Mocha testing framework and using should as assert. In our next post we will include the testing of a Rest API using Mocha, Should.js and Supertest.
Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.
No comments:
Post a Comment