Sönke Rohde

Testing Node.js Express Routes

Lately I needed some tests for an Express Node.js project I was working on and I was surprised how easy and minimalistic the code can look like with CoffeeScript. Check out this gist:

I am using should.js as the assertion library and mocha as the testing framework. In this example I am testing a login function. My Node.js route (api.coffee) is being imported and then I’ll first test if the login function actually exists. After that I am invoking the login function and make assertions against the result. The implemented function signature looks like this:

1
exports.login = (req, res) ->

The parameters are request and response. This route is using GET so for the request parameter we’ll specify the query parameters. When the implementation is done with the login execution it’ll call res.send(result) so it’s perfect to hook into that as well and we can do assertions against the result type and value.

If you are new to CoffeeScript this might look a bit cryptic but let me show you how the JavaScript would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Generated by CoffeeScript 1.6.2
(function() {
  var api, should;

  should = require('should');

  api = require('../../routes/api');

  describe('api', function() {
    return describe('#login()', function() {
      return it('should login a user', function(done) {
        api.login.should.be.a('function');
        return api.login({
          query: {
            email: "foo@gmail.com",
            password: "secret"
          }
        }, {
          send: function(result) {
            result.should.be.a('object');
            result.email.should.equal("foo@gmail.com");
            return done();
          }
        });
      });
    });
  });

}).call(this);

Comments