I am testing my Node.js application with Jest and Supertest. I have multiple tests but only 2 of them fail occassionally with message "read ECONNRESET". I haven't found any constant pattern in failures because sometimes they both fail, sometimes another one fails and sometimes they both pass.
My database is MongoDB.
This is the 1. test which fails sometimes:
test('user cannot upload image without token', async (done) => {
await api
.patch(`/api/users/${authenticatedUser.id}/picture/add`)
.attach('image', path.join(__dirname, 'test-image.jpg'))
.expect(401)
.expect('Content-Type', /application\/json/)
const user = await User.findOne({_id: authenticatedUser.id})
expect(user.image).toBeFalsy()
done()
})
This is the 2. test which fails sometimes:
test('user cannot upload image with invalid token', async (done) => {
await api
.patch(`/api/users/${authenticatedUser.id}/picture/add`)
.attach('image', path.join(__dirname, 'test-image.jpg'))
.set('Authorization', `bearer ${helper.invalidToken}`)
.expect(401)
.expect('Content-Type', /application\/json/)
const user = await User.findOne({_id: authenticatedUser.id})
expect(user.image).toBeFalsy()
done()
})
One thing in common with these two tests is that they both give the following warning when tested individually:
● Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "connected to MongoDB".
17 | mongoose.connect(config.MONGODB_URI, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true })
18 | .then(() => {
> 19 | console.log('connected to MongoDB')
| ^
20 | })
21 | .catch((error) => {
22 | console.log('error connection to MongoDB:', error.message)
at BufferedConsole.log (node_modules/@jest/console/build/BufferedConsole.js:199:10)
at mongoose.connect.then (app.js:19:13)
But this warning is given also when these tests occassinally pass, and with other tests when tested individually. Maybe it is somehow related to this ECONNRESET, or maybe not...
I'd really appreciate some tips on how to fix this small but annoying issue. Thanks in advance!
The complete test file and the whole project can be found: here on GitHub