Using Supertest in Mocha to test Node.js Express API and MongoDB Using Supertest in Mocha to test Node.js Express API and MongoDB mongoose mongoose

Using Supertest in Mocha to test Node.js Express API and MongoDB


I think it is because of the asynchronous nature of request calls. You need to wrap the second request in a callback, so that it will only be executed when the first one is completed and your test object is put into the database.

Also, .eql(couponTwo) will fail in your case anyway, because your response is an array containing the object that was put, and you compare it directly to the object. Use .eql([couponTwo]) if you want to make sure that it is the only element in the array, or just use .containEql(couponTwo).

Try this:

request(url).post('/coupons').set('Content-Type', 'application/json').send(couponTwo).end(function () {  request(url).get('/coupons').end(function (err, res) {    if (err) throw err;    console.log(res.body);    res.body.should.containEql(couponTwo);    done();  });});