title: Using Supertest in Mocha to test Node.js Express API and MongoDB
body: <p>I have been searching this site and the web for a while now and I cannot find a solution to this problem. I am trying to test the REST function of my API, but the PUT test never seems to work. Each time the test runs in mocha, I get the error "Uncaught assertion error: expected [] to equal {objectData}" where objectData is the json representation of the object I am trying to post (named couponTwo).</p>
  
  <p>I have a feeling the problem lies in the beforeEach function, as it clears the database before each test, which needs to be done for many other tests to run correctly. Here is the test code:</p>
  
  <pre><code>var config = require('../config/config');
  var mongoose = require('mongoose');
  var should = require('should');
  var request = require('supertest');  
  var Coupon = require('../models/coupon');
  var url = require('../config/config').test.url;
  
  process.env.NODE_ENV = 'test';
  
  beforeEach(function (done) {
  
    function clearCollections() {
      for (var collection in mongoose.connection.collections) {
        mongoose.connection.collections[collection].remove(function() {});
      }
      return done();
    }
  
    if (mongoose.connection.readyState === 0) {
      mongoose.connect(config.test.db, function (err) {
        if (err) throw err;
        return clearCollections();
      });
    } else {
      return clearCollections();
    }
  });
  
  afterEach(function (done) {
    mongoose.disconnect();
    return done();
  });
  </code></pre>
  
  <p>Here is the  that is supposed to test that an object exists in the database after a PUT:</p>
  
  <pre><code>describe('#post', function () {
  it('should return a coupon object after post', function (done) {
  request(url).post('/coupons')
    .set('Content-Type', 'application/json')
    .send(couponTwo)
  
    request(url).get('/coupons').end(function (err, res) {
      if (err) throw err;
      console.log(res.body);
      res.body.should.eql(couponTwo);
      done();
    })
  })
  })
  </code></pre>
  
  <p>I apologize if the answer to this question is obvious and I am missing something fundamental, but I have reached a roadblock. Thanks for your help!</p>