Mocha: Advanced tips to easily test asynchronous fonction

♻ Basic usage

Everyone knows Mocha’s done callack :

it('should work without error', function(done) {
  testedfunction()
    .then(() => done();)
    .catch((err) => done(err); )
  );
});

This is simple, but there’s 2 points to notice here:

    1. I use then(() => done();) and not then(done) : the then(() => {}) form, done is executed with this poiting to Mocha while the other one this is the promise and done may no work.
    2. I use then(…).catch(…) and not then(() => {}, (err)=>{}), here is why:
it('should work without error', function(done) {
  testedFunction()
    .then((result) => {
      assert(result === 'yes'); 
      done(); 
    })
    .catch((err) => done(err); ) 
    // test fails if testedFunction failed or if result != 'yes'
  );
});
it('should work without error', function(done) {
  testedFunction()]
    .then(
      (result) => {
         assert(result === 'yes'); 
         done(); 
       },
       (err) => done(err); ) 
       // test fails if testedFunction failed only. error handler is not called
       // if assert failed
    }
  );
});

♻ Better promise usage:

It is less known that one can return a promise to Mocha:

it('should work without error', function() {
  return testedFunction()
    .then((result) => {
      assert(result === 'yes');
    });
  );
});

♻ Even better: async/await

Since 7.0.0, node support async/await function, and an async function returns a promise “under the hood”, so that we can write tests using aync function:

it('should work without error', async function() {
  const result = await testedFunction();
  assert(result === 'yes');
});

And this is true also for hook functions:

before(async function() {
  await db.connect();
);

 


I use extensively asyn function in my tests: this make my code easier to write, to read and to maintain: so my advice is: try them !


 

See you and have a nice code 🙋

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s