How you can do TDD in your express.js server with Jest and SuperTest
Hello, today I'll share how you could do TDD in your express.js apps,
write express.js apps are fun and easy, but an important thing is the unit test to ensure that your endpoints are working as expected, then why not write your express server using TDD patter?
what is TDD:
Test-driven development (TDD) is a software development process relying on software requirements being converted to test cases before software is fully developed
TL;DR
You can do TDD in your express server, easily using SuperTest package and Jest, what is SuperTest?:
SuperTest: Super-agent driven library for testing node.js HTTP servers using a fluent API..
And Jest is the most popular tool for do unit test to react apps, but Jest is more than that:
Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
Jest supports node, and used with SuperTest you can do unit testing to your Express.js Server lets do it:
Follows the TDD pattern, we first write our test before the code implementation.
`server.test.js`
const request = require('supertest') const app = require('./server') test('Get the Home path', (done) => { request(app).get('/').expect(200, done) })
And it's all, first, we import the `SuperTest` super agent, and the express app, after, we use the jest `test` method to write our first test, we use the `done` parameter to running asynchronous test, for saying to jest when the test finish, at the last, we do a `request(app).get('/anything')` for test a `get` method.
Let's write our code implementation:
`server.js`
const express = require('express') const app = express() app.get('/', (req, res) => { res.sendStatus(200) }) module.exports = app
the key point here is that the `listen` call must be placed apart, otherwise the test job never ends, we can run the `listen` in our `index.js`
`index.js`
const app = require('./server') const port = 3000 app.listen(port, () => { console.log(`App listening an https://localhost:${port}`) })
We can test any endpoint, get, post, put, delete
here an example of a get endpoint validating the response:
const request = require('supertest') const app = require('./server') test('Sum endpoint', (done) => { request(server) .get(`/api/sum/${1}/plus/${1}`) .expect(200, { result: 2 }, done) }) })
And here the code implementation:
server.get('/api/sum/:a/plus/:b', (req, res) => { res.status(200) const a = Number.parseInt(req.params.a) const b = Number.parseInt(req.params.b) const result = a - b res.json({ result }) })
This is a basic explanation but is a good start point to do TDD and Unit Test in general, to your express.js server. in the SuperTest repo, you can find more information about the library.