Issue
I’m trying to understand unit testing in Express + Mocha/Chai.
The API call I’m trying to test seems to stop after the first async function and times out, see relative code and console output below.
I’m not sure if I’m missing something in the API itself or in the test!
// controller.js
const { Alert } = require('../models');
exports.addAlert = async (req, res) => {
const username = req.body.uploader !== "" ? req.body.uploader : "anonymous"
const rowNumber = await Alert.count()
const title = req.body.title !== "" ? req.body.title : parseInt(rowNumber) + 1
const addedAlert = await Alert.findOrCreate({
where: {
coordinates: req.body.coordinates
},
defaults: {
username: username,
path: req.file.path,
title: title
}
})
addedAlert[1] ?
res.send(200).render('home', {
formMessage: `Added alert ${title}`
}) :
res.send(303).render('home', {
formMessage: 'Coordinates already taken.'
})
};
// test.js
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../../app');
let should = chai.should();
chai.use(chaiHttp);
describe('/POST alert', () => {
it('it should POST an alert', (done) => {
chai.request(server)
.post('/add-alert')
.send({ username: "foo", title: "bar", coordinates: "baz", path: "foo/bar/baz" })
.end((err, res) => {
console.log(res.body)
done();
});
});
});
//mocha tests/**/*.* --exit
/POST alert
Executing (default): SELECT count(*) AS `count` FROM `Alerts` AS `Alert`;
1) it should POST an alert
/*
** Other tests that are working fine
*/
1 failing
1) /POST alert
it should POST an alert:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/*..*/test.js)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
Solution
I solved my own problem: Mocha wasn’t proceeding because I wasn’t passing it the file I had uploaded with Multer in the form.
This worked:
it('it should POST an alert', async function() {
await request(server)
.post('/add-alert')
.set('Content-Type', 'multipart/form-data')
.field('uploader', 'foo')
.field('coordinates', 'bar')
.field('title', 'baz')
.attach('image',
fs.readFileSync('./dist/images/image-1617995909552.jpg'),
'image-1617995909552.jpg')
.expect(200)
});