How to test async code with mocha using await?

by mallory_cormier , in category: Javascript , 18 days ago

How to test async code with mocha using await?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 17 days ago

@mallory_cormier 

In order to test async code with Mocha using await, you need to use the async keyword in your test function and then use await to wait for the async operation to complete. Here is an example of how you can test async code with Mocha using await:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const assert = require('assert');

async function asyncFunction() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('done');
    }, 1000);
  });
}

describe('Async code test', function() {
  it('should return "done" after 1 second', async function() {
    const result = await asyncFunction();
    assert.strictEqual(result, 'done');
  });
});


In this example, we have an async function asyncFunction that returns a Promise which resolves after 1 second. In our Mocha test, we use the async keyword on the test function and use await to wait for asyncFunction to complete. We then use the assert.strictEqual method to verify that the result is equal to 'done'.


When running this test with Mocha, it will wait for the async operation to complete before moving on to the next test, ensuring that the async code is properly tested.