dcsan
dcsan

Reputation: 12275

how do async/await testing with TypeScript and mocha

I have a simple async mocha test, but the done() callback never seems to get called.

describe("RiBot", function() {
  it("should start with a random topic", async (done) => {
    await RiBot.init();
    let topic = RiBot.getTopic("testuser")
    assert.equal(topic, "FAILHERE");
    done()
  })
})

In this case the assertion should fail but instead I just get a timeout.

  RiBot
  RibotTest topic +0ms undefined
    1) should start with a random topic


  0 passing (2s)
  1 failing

  1) RiBot should start with a random topic:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

edit: when i run just as standard JS code with an assert:

async function testRiBot() {
  try {
    await RiBot.init()
    let topic = RiBot.getTopic("testuser")
    debug('topic', topic)
    assert.equal(topic, "FAILHERE", 'fail match on topic');
  } catch(err) {
    debug("err", err, err.stack)
  }
}

I do get an exception thrown as the error.

  RibotTest err +2ms { [AssertionError: fail match on topic]
  name: 'AssertionError',
  actual: 'undefined',
  expected: 'FAILHERE',
  operator: '==',
  message: 'fail match on topic',
  generatedMessage: false } AssertionError: fail match on topic
    at /Users/dc/dev/rikai/boteditor/test/RiBot_test.js:19:20
    at next (native)
    at fulfilled (/Users/dc/dev/rikai/boteditor/test/RiBot_test.js:4:58)
    at process._tickCallback (node.js:412:9)

Can someone provide a simple example using a typescript async/await and mocha?

Upvotes: 5

Views: 9855

Answers (1)

Dave Templin
Dave Templin

Reputation: 1824

Try defining your test like this... (and at the same time remove your done call)

it('should start with a random topic', async function () {
    // ...
});

Note if your test returns a Promise then the mocha framework will look for the Promise to be resolved or rejected rather than a done callback. Note async functions always return a Promise.

Also it's a best practice to avoid using arrow functions to define tests otherwise you can't access the correct this context from the test (i.e. you can't do things like calling this.title within your test code).

Upvotes: 10

Related Questions