Beginning Node.js – Testing – part 5

Testing for the newbie

To test your Node API’s you will need to install the following dependencies:

  • Mocha. Mocha is a library to run tests, AKA a test runner, or test infrastructure. Install it globally, like so: npm install -g mocha.
  • Chai. With Chai you can use “assert that.. ” or “should be.. ” or “expect that.. “. Depends on the test philosophy you are using (BDD, TDD and the likes)
  • Superagent. Superagent is a library that can test a web api, like so: superagent.get(‘http://localhost:3001/food’)

Of course there are alternatives (Jasmine, Should ..) but in my humble experience the above 3 work just fine. At first I was wondering why I needed so many libraries but I guess this all about the freedom to mix and match the modules you like the most. Which is quite nice.

Test the API

This is an example test to the ‘list’ function of all the food. Does the API return a JSON array? Well, it should, so I expect it to be.

First, Create a folder named ‘test’
Then put a file in it. (e.g. test1.js), with these contents:

var superagent = require('superagent');
var chai = require('chai');
var expect = chai.expect;

describe("Food JSON api", function() {  

  it("should return a json array", function(done) {
    superagent.get('http://localhost:3001/food')
      .end(function(err, res) {
        expect(err).to.eql(null);
        expect(res.status).to.equal(200);
        expect(res.body.success).to.equal(true);
        expect(res.type).to.equal("application/json");
        done();
      });
  });

}

Now run the test with the command: mocha.

[jacqueline@pc01 Restaurant]$ mocha

  Food JSON api
    ✓ should return a json array 


  1 passing (39ms)

Another test

With SuperAgent you can also test a POST action (be sure not to use your production db, but more about different environments later).

it("should post a new piece of food", function(done) {
    superagent.post('http://localhost:3001/food/')
      .send({
        name: "awesome food in test db from env", description: "awesome food description", price: "16,00"
      })
      .end(function(err, res) {
        expect(err).to.eql(null);
        expect(res.body._id).to.not.be.eql(null);
        id = res.body._id;
        done();
      });
  });

Run the test:

[jacqueline@pc01 Restaurant]$ mocha


  Food JSON api
    ✓ should return a json array 
    ✓ should post a new piece of food 


  2 passing (38ms)

So, this was just a wee intro to testing web API’s. There is lots more to discover about this subject!

I just put the code online at github. This is still a work in progress though.

%d bloggers liken dit: