Friday, June 12, 2015

Node.js Application Testing With Mocha

Testing is one of the most important thing in software development cycle. In a Node Express application we must properly test both controllers and models. In this post I will use Mocha as the test framework, should.js as assertion library and SuperTest for HTTP assertions. Mocha supports both TDD and BDD tests.
I will continue this post with the implementation which I have done in my previous post.
First we will install mocha globally.
Then install should.js and supertest as npm dev dependencies.
Now we need to configure our test environment. For that add test.js into config/env folder and add content like below.
In mocha test file, first you need to describe about your test. The describe blocks can be nested. Assume we need to write test for the following student.server.model.js model. Then you can create student.server.model.tests.js test file in app/tests folder like below.
In the test case, we will check two scenarios. One is, if we assign all values appropriately whether the student get saved. And the other one is, without passing required firstName whether the save function gives an error result. "beforeEach" and "afterEach" functions will run before and after each test is executed.
Now we will write code for test student.server.controller.js file. In here I will check "/api/students/" route functions.
Now it's time to run our mocha tests. In command prompt first set Environment as test.
Reason for that is, in server.js expects current environment.
Then run "mocha --reporter spec app/tests" command. The output will be look like below.
If you need to generate test results in a document, you could try "mocha-unfunk-reporter".
Download Source Code from GitHub.

No comments:

Post a Comment