0

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)
    })
  }
Mick F
  • 7,312
  • 6
  • 51
  • 98
  • If you're using Mocha (or another test framework that supports promises), there's a third option: `it(..., () => { return foo.bar().should.eventually... })` (because `eventually` returns a promise, and when a test case returns a promise, Mocha will handle it properly without the need for a callback) – robertklep May 10 '17 at 09:16

2 Answers2

1

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');
})
Troopers
  • 5,127
  • 1
  • 37
  • 64
0

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.

vorillaz
  • 6,098
  • 2
  • 30
  • 46