0
votes

I am new to mocha testing but when I write the code as so

var assert=require('assert');
// ../ --->go up a directory
var MarioChar=require('../models/marioCharacter');

  //Describe tests
 //describe("description",function that executes tests)
 describe('Saving Records',function(done){
  //create tests
  //it blocks -describes a single tests
  //it("description",function that executes a test)
it('Saves a record to the database',function(){
    //if assert evaluates to true, the test passes
    //otherwise the test fails
    //marioCharacter model is expecting the properties of the object
    // that adhere to its set Schema
    var mario=new MarioChar({
      name:"mario"
    });
    mario.save().then(function(){
      console.log("saved");
      done();
    });

      //then need to save this character to the database
      //saves the character to the set database
      //save() is an async request so cannot assert save() directly
      //save implements the promise interface
});
//next test
});

It works however, when I pass the done through the it block instead of the describe block it reads out the error " Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves." whats going on here?

1
I think the done parameter should be on the individual test. So like it('Saves a record to the database',function(done){...} - sbrass
Ya but when I did that it does not work - bookofeli8
Did you remove it from the describe function? - sbrass
Sorry, I was looking at it wrong. Mocha should support promises, so you don't need done unless you're using callbacks. You can either just do assertions after the promise is done - i.e. in then(), or you can see my answer for how to use async/await - sbrass

1 Answers

0
votes

An easier way to test promises might be by using async/await. Your test would look like

it('Saves a record to the database', async function(){
    var mario=new MarioChar({
      name:"mario"
    });
    await mario.save();
    console.log('saved');
    // Any assertions can go here after mario has been saved
});