- Practice writing tests with Jest
- Catch any bugs in your project's API code
Now that you've tested your model classes, you'll use jest to ensure your API's work as expected.
- Install
supertest
by runningnpm install supertest --save-dev
- Install and setup
jasmine
if you have not yet done so, see previous lesson for instructions. - Supertest needs the express
app
that you create in yourindex.js
file. We're going to move theapp
creation and setup to aserver.js
file so that your tests can access it easily. See this blog for an example.
// server.js file
const express = require('express');
... all your imports
function createServer() {
const app = express();
// all your app.use setup and app routes
return app
}
module.exports = createServer
// index.js file
const createServer = require("./server")
app = createServer()
const PORT = 3000;
app.listen(PORT, () => {
console.log(`The application is running on localhost:${PORT}`);
})
- In the
spec
folder you created in the previous exercise, create a fileapiSpec.js
and copy the sample code below:
const createServer = require('../server');
const request = require('supertest');
describe('The application', function () {
it('creates and deletes the event successfully', function (done) {
const createParams = {
eventDate: { year: 2020, month: 10, day: 11 },
eventLocation: 'home',
eventCategory: 'art',
eventID: '1',
eventName: 'paint by numbers'
};
const app = createServer();
// create the event
request(app)
.post('/event')
.send(createParams)
.set('Accept', 'application/json')
.expect(200, done);
// now fetch the events
request(app)
.get('/events')
.expect(200)
.then((response) => {
const events = response.json();
assert(events.length, 1); // 1 event
assert(events[0].id === '1');
done();
})
.catch((err) => done(err));
// now delete the event
const deleteParams = { eventID: '1' };
request(app)
.delete('/event')
.send(deleteParams)
.set('Accept', 'application/json')
.expect(200, done);
// now fetch the events again
request(app)
.get('/events')
.expect(200)
.then((response) => {
const events = response.json();
assert(events.length, 0); // no events
done();
})
.catch((err) => done(err));
});
});
- The sample test above checks that the event creation and deletion work as expected. Update it to match your API routes, expected parameters, and expected body format (the tested app expects JSON input, but your app may differ). Run
npm test
to run all your tests, ornpm test spec/apiSpec.js
to run only the API tests. - Add a test for your event search API.
- Add at least one more test of your choice. What else could be useful to test in your code?