6.7 Testing Express Application : Part II


Supertest: https://github.com/visionmedia/supertest
Install Supertest: npm i supertest --save-dev


Export app of express
Add module.exports.app = app; at the bottom of server.js


In server.test.js

const request = require('supertest');
const app = require('./server.js').app;
it('should return hello world response', (done) => {
request(app)
.get('/')
.expect('hello world')
.end(done);
});

expect(200) requires the status code to be 200.
Example:

request(app)
.get('/')
.expect(200)
...

Also OK with JSON webpage

app.get('/', (req, res) => {
res.send({
name: 'Jude',
age: 19
});
});

The test part would become

request(app)
.get('/')
.expect({name: 'Jude', age: 19})
...

More flexibility

const request = require('supertest');
const app = require('./server.js').app;
const expect = require('expect');
it('should return hello world response', (done) => {
request(app)
.get('/')
.expect(200)
.expect((res) => {
expect(res.body).toInclude({name: 'Jude'});
})
.end(done);
})

This is an instance of using combination of Supertest and Expect.


Exercise: Make a new route and test it.

app.get('/users', (req, res) => {
res.send([
{
name: 'Jude',
age: 19
},
{
name: 'Troy',
age: 19
},
{
name: 'Harry',
age: 30
}
])
})

Test:

it('should return my user objects', (done) => {
request(app)
.get('/users')
.expect(200)
.expect((req)=>{
expect(req.body).toInclude({name: 'Jude', age: 19});
})
.end(done);
})

Uncaught Error Fix

if(!module.parent){
app.listen(3000);
}