Skip to content

Testing

Koustuv Sinha edited this page Jan 24, 2016 · 4 revisions

For every API we write, we will create individual test cases. It is a good practice to write test cases first and then write the API.

We are using mocha and chai to test our app. Also, supertest is used to query the HTTP requests. Whenever a commit is done in this repository, our friendly butler Travis runs the test cases and reports back to us. Let us continue from the previous API we made.

Now we want to test our API and see whether it is returning an Array of books. Create a new file books.js in test folder, and write the following :

/**
 * Books testing suite
 */

'use strict'

var request = require('supertest')
var app = require('../app')
var expect = require('chai').expect

describe('Apna Library Testing suite', function () {
  
  // tests whether the api endpoint is accessible or not
  it('should return books api', function (done) {
    request(app)
      .get('/api/books')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done)
  })

  // tests whether the api returns an array or not
  it('should return an array of books', function (done) {
    request(app)
      .get('/api/books')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function (err, res) {
        if(err) console.log(err)
        var books = res.body
        expect(books).to.be.an('array')
        done()
     })
  })

})

After you are node, type npm test to test out. If everything is ok, it should pass with all green!

Express server listening on port 3000
  Apna Library Testing suite
    ✓ should return books api (42ms)
    ✓ should return an array of books

  Apna Library Dummy test stub
    ✓ should expose api endpoint


  3 passing (86ms)

Clone this wiki locally