Take the 2-minute tour ×

I am working with Mocha and am trying to test an API that I am in the process of building.

I am having trouble understanding where to place the done() function.

If I place it where it is now, it doesn't execute the callback function of User.findOne().

If I place the done at the bottom of the callback function of User.findOne(), then it creates a timeout.

I am relatively new to async and this done function, so can someone help explain why these two cases happen, and how to fix the code so that it will test correctly in Mocha?

describe('POST /signup', function() {
  before(checkServerIsRunning); // Need to implement
  it('create a new user if username is unique', function(done) {
      method : 'POST',
      url    : url + '/signup',
      json   : true,
      body   : JSON.stringify({ 
        username : 'test',
        first    : 'first',
        last     : 'last' })
      function (err, res, body) {
        if (err) {
        else {
          User.findOne( { username: 'test' }, function(err, user) {
            user.should.have.property('username', 'testy');
            user.should.have.property('firstName', 'first');
            user.should.have.property('lastName', 'last');
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

You should place done() inside the called to findOne.

If you're finding that it times out then either findOne is never calling its callback (which is an error!) or it's taking too long to execute.

In this case you could up the timeout by sticking something like this.timeout(5000) at the beginning of the test (which increases the timeout to 5 seconds).

In general you wouldn't usually want tests that slow though, so maybe try and figure out why it takes so long.

share|improve this answer
Thanks, I found out that I wasn't connected to my database (silly me!) which is why it was timing out. It should go inside findOne! –  aikitect Aug 7 '12 at 16:16
add comment

Your Answer


