Get #Amazon #Prime for this #holiday #amazonprime #christmas #2019

#JavaScript - #Mocha #Chai async await promise test

How to test promises / async await functions using Mocha test runner and Chai ?

Mocha
Mocha

Chai
Chai 
To catch an error from an await function, you can use try and catch blocks like the following:

try {
  await asyncFunction(2);
} catch (err) {
  expect(err).to.be.an.instanceof(Error);
  expect(err.message).to.equal('Service is not available');
}

Testing resolved and rejected promises

Expect resolved promises

// using done callback
it('test resolved promise', (done) => {
  asyncFunction(arguments)
    .then((response) => {
      assert.isString(response);
      expect(response).to.be.a('string');
      expect(response).to.have.lengthOf(2);
      done();
    })
    .catch((err) => {
      done(err);
    });
});

// using async await, so you need to use es2017
it('test resolved promise', async () => {
  const response = await asyncFunction(arguments).catch((err) => { throw err; });
  assert.isString(response);
  expect(response).to.be.a('string');
  expect(response).to.have.lengthOf(2);
});

Expect rejected promises

it('test rejected promise', (done) => {
  asyncFunction(arguments)
    .then(() => {
      assert.fail(0, 1, 'Expected rejected promise'); // to fail a test
      done();
    }, (err) => {
      expect(err).to.be.an.instanceof(Error);
      expect(err.message).to.equal('Service is not available')
      done();
    });
});

it('test rejected promise', async () => {
  const errorHandler = function (err) {
    expect(err).to.be.an.instanceof(Error);
    expect(err.message).to.equal('Service is not available');
  };

  const response = await asyncFunction(arguments).catch(err => errorHandler(err));
  expect(response).to.be.an('undefined');
});

Thanks for reading!

Jun