What is the difference between calling chai-as-promised with or without a notify method?

430 Views Asked by At

I'm using chai and chai-as-promised to test some asynchronous JS code.

I just want to check that a function returning a promise will eventually return an Array and wrote the 2 following tests:

A:

it('should return an array', () => {
    foo.bar().should.eventually.to.be.a('array')
})

B:

it('should return an array', (done) => {
    foo.bar().should.eventually.to.be.a('array').notify(done)
})

Both are passing OK, but only the B option actually runs the full code included in my bar() function (ie displaying the console.log() message from the code below). Am I doing something wrong? Why is that so?

bar() {
    return myPromise()
    .then((result) => {
      console.log('Doing stuff')
      return result.body.Data
    })
    .catch((e) => {
      console.err(e)
    })
  }
2

There are 2 best solutions below

0
On BEST ANSWER

What test library do you use? Mocha, Intern or other? For Mocha and Intern, you must return the promise from your test method:

it('should return an array', () => {
    return foo.bar().should.eventually.to.be.a('array');
})
0
On

Testing a promise means that you’re testing asynchronous code. Notify and done callback sets up a timer and waits for the promise chain to finish up executing.

The second approach is the correct one since you may need to test chained promises.

Take a look at this tutorial which got me into asynchronous unit testing.