I wrote the testing code and it worked fine but after I added other routes that didn't relate to the current code, the code became corrupted, especially at this point:
1) "before each" hook for "should create new todo": Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test`.
const todos = [{
_id: new ObjectID(),
text: 'first test todo',
completed: false,
completedAt: null
}, {
_id: new ObjectID(),
text: 'second test todo',
completed: true,
completedAt: 333
}];
beforeEach((done) => {
Todo.remove({}).then(() => {
return Todo.insertMany(todos);
}).then((docs) => {
done();
});
})
describe('post /todo', () => {
it('should create new todo', (done) => {
let text = 'here from supertest';
request(app)
.post('/todos')
.send({
text
})
.expect(200)
.expect((res) => {
expect(res.body.text).toBe(text);
})
.end((err, res) => {
if (err) {
return done(err);
}
Todo.find({
text
}).then((res) => {
expect(res.length).toBe(1);
expect(res[0].text).toBe(text);
done();
})
.catch((e) => {
done(e);
});
});
});
});
The whole project is in this github libary called TestMongo, where you can check the last two commits that have the issues with testing that I face but when you try it by postman it works fine. When one reverts to the third commit from the end, the testing works correctly.
Probably we need to increase the timeout of test to bigger number
beforeEach(function(done) { // dont use arrow function to use this.timeout
this.timeout(5000); // override default 2000 ms
Todo.remove({}).then(() => {
return Todo.insertMany(todos);
}).then((docs) => {
done();
});
})
Hope it helps