harumph
harumph

Reputation: 179

Mocha tests for expressjs 4, spying on a function called in a promise, tests fail silently

I have some tests that look like this:

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(someSpy).to.have.been.called
    done()
  })
})

If the assertion in that test fails, it will fail silently, and the test itself will timeout because done() is never reached. For example, this:

it('does stuff', function(done) {
  expect(1).to.equal(2)

  somePromise.then(function () {
    expect(someSpy).to.have.been.called
    done()
  })
})

will fail with a nice error explaining that we were expecting 1 but got 2. However, this:

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(1).to.equal(2)

    expect(someSpy).to.have.been.called
    done()
  })
})

will fail due to timeout. I gather the issue is that I'm not in the "it" context, but what's the best way to deal with this?

Upvotes: 0

Views: 112

Answers (1)

nowk
nowk

Reputation: 33171

Failed assertions are basically thrown errors. You can catch them like you can any error in a Promise.

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(1).to.equal(2)

    expect(someSpy).to.have.been.called
    done()
  })
  .catch(done)
})

Upvotes: 2

Related Questions