0

I've seen this https://mochajs.org/#asynchronous-code regarding how to set-up tests for asynch code. It makes sense, but I am not sure where to put the actual.

So if this is my test:

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(done);
    });
  });
});

Where would I then put something to check the user object's name field or some similar such result?

Thanks!

Bren
  • 3,516
  • 11
  • 41
  • 73

2 Answers2

1

user.save returns a callback. Instead of passing in only done you you should pass in a function that executes the needed checks and then calls done.

for example:

user.save((err) => {
 //do the needed checks on user
 done()
})

by the way, the user object that you instantiated, contains both name and id after you called save on it. Look here for more infos

Nicola Pedretti
  • 4,831
  • 3
  • 36
  • 42
  • That makes sense. My issue now is that instead of getting an assert failure message I get a timeout, but at least it is a failure. – Bren Aug 07 '17 at 21:50
  • @Bren, that usually happens when done does not get called, are you sure nothing breaks before getting to done causing it not to get called? also, I doubt it, but it can also be the case that it actually takes a long time to do all you need to don before done is called. In that case look here : https://stackoverflow.com/questions/16607039/in-mocha-testing-while-calling-asynchronous-function-how-to-avoid-the-timeout-er – Nicola Pedretti Aug 07 '17 at 21:55
  • It results in an unhandled promise, so that is probably to blame. The promise is a few levels lower than what I am testing. – Bren Aug 07 '17 at 22:00
  • Yeah, that's probably it then! – Nicola Pedretti Aug 07 '17 at 22:10
0

By the looks of your code I assume, you're using Mongoose or something similar, in which case the callback of the save() function has 2 parameters, an error and the saved document.

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(function (err, doc) {
        assert.equal(doc.name, 'Luna')
        done()
      });
    });
  });
});