Sometimes, we want to test an Express app with Mocha.
In this article, we’ll look at how to test an Express app with Mocha.
How to test an Express app with Mocha?
To test an Express app with Mocha, we can make requests in our tests to the endpoint we’re testing with supertest
.
For instance, we write
const request = require('supertest')
const {
app
} = require('./express-app')
const assert = require("assert");
describe('POST /', () => {
it('should fail', (done) => {
request(app)
.post('/')
.send({
'imgUri': 'foobar'
})
.expect(500)
.end((err, res) => {
done();
})
})
});
to call it
with a callback with the test code.
In it, we call request
with app
to run the app
.
And then we call post
to make a POST request.
send
sends the POST request body.
We then call expect
to test the returned response code.
And then we call done
in the end
callback to finish the test.
Conclusion
To test an Express app with Mocha, we can make requests in our tests to the endpoint we’re testing with supertest
.