I have a test for Mocha, using expect and supertest, that works just fine. But I don't understand how it works. I'm using express as my server, along with mongodb and mongoose.
I understand how testing for .get() would work, that makes perfect sense. Youtube tutorials and the mocha documentation haven't been able to offer me any sort of real insight.
describe('DELETE for a specific todo', ()=>{
it('should delete a todo', (done)=>{
let id0 = todos[0]._id
request(app)
.delete(`/todos/${id0}`)
.expect(200)
.expect((response)=>{
expect(response.body.todo._id).toBe(id0)
});
.end((err, res)=>{
if(err){
return done(err)
}
Todo.findById(id0).then((todo)=>{
expect(todo).toNotExist();
}).catch((err)=>done(err))
})
});
it('should fail to find ID in db', (done)=>{
request(app)
.delete(`/todos/${new ObjectID()}`)
.expect(500)
.end(done)
});
it('should fail due to invalid ID', (done)=>{
request(app)
.delete('/todos/999')
.expect(404)
.end(done)
});
});
This code works just find, the model/collection is perfectly OK, but how is it that mocha tests .delete without actually deleting something from my database? Does it create a mock data base and then run said tests on it? Does it delete something, run the test, and then undelete it? I just don't understand what mocha/supertest is doing when I use request(app).delete().I mean, it MUST be modifying the collection my model specifies, or else if would be impossible for Todo(which is the model name)to work properly....
Your question isn't really about Mocha, but more specifically about how Supertest works.
Supertest provides its own expect
method which is what gets invoked when you chain it through Supertest. Supertest is itself a wrapper for Superagent
which provides the various request methods. In this case, the .delete
method of Superagent will literally invoke a HTTP DELETE request to your express server, and unless you are doing some form of mocking in the setup of your Express server, then it will perform whatever operations your Express server has for that route.
TL;DR: Supertest does not perform any mocking, your code is expected to perform any setup for mocking in the Express server that you connect Supertest to. Without that, it will delete data or perform whatever other logic your Express server is set up to do on the specific route.