This is going to be a multi-part series of posts to detail my current process for unit testing a full stack javascript application. Consider this my brain dump of information that I’ve either found from others posts, found in the official documentation or I’ve just been doing it that way because it makes sense in my head.
Unit testing has to be one of the most important aspects for any developer that’s serious about their work to start doing, and be disciplined enough to continue doing it regardless of some of the mind-numbing aspects of it.
Starting off we will be establishing the testing procedure for our javascript backend, which consists of node/io.js using express to serve up our restful api. I was shocked once I finally got everything working properly, with how easy it was to get going.
You will need to npm install the following modules:
- mocha
- supertest
- chai
1 2 |
# npm install -g mocha # npm install --save-dev supertest chai |
These are the only modules necessary to do all your assertion/expect testing.
Once installed, I would suggest creating a test folder at the root of your application directory. Inside of this directory I will typically split groups of tests for each Controller in my application. Ending up with something like this:
1 2 3 4 5 6 7 |
/my-express-app /controllers /database /test /unit /fixtures myControllerSpec.js |
The controller specs should be setup something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var request = require('supertest'), express = require('express'), chai = require('chai'); var expect = chai.expect; var app = require ('../app.js'); // path must be relative to current file. describe('Unit: UserController', function(){ var resource = 'user'; describe('GET /user', function(){ it('responds with all the users and status code 200', function(done){ request(app) .get('/' + resource) .end(function(err, res){ expect(res.statusCode.to.equal(200); expect(res.body.user).to.be.defined; done(); }); }); }); }); |
Now with that setup, you can just run from your project root, from the command line:
1 |
mocha -w test/unit/**/*.js |
and it will watch all test files for changes and run all your tests again, if a change is detected.
That’s all there is to it for getting true automatic testing going for your existing or next express api.
The next post will be for how to properly setup testing for the angular end of your application.