DEV Community

Alisson Zampietro
Alisson Zampietro

Posted on • Edited on

Testing Promise Rejection with Chai

I've been using chai to test my application, but today i faced a curious problem. I've been testing if the exception thrown in the try/catch matches with i expect, let’s check a snippet of my test code:

it('Test if validate the customer externalId', function() {
  let flawedCustomerArgs = [{
    name: 'John',
    details: 'test'
  }]

  // we need to bind the parameters flawedCustomerArgs, 
  // because in the execution context the cai method "expect"
  // will invoke the "importCustomer()" method
  chai
    .expect(ImportService.importCustomer.bind(ImportService, flawedCustomerArgs))
    .to
    .throw('Field externalId not defined for Customer');
})
Enter fullscreen mode Exit fullscreen mode

But let's suppose that now i need my method importCustomer to be async, the snippet code above won't work, because it will return a promise and the exception that i'm expecting is coming in the Promise Rejection.

How can i get this rejection in the chai?

If we don't want to change our previous script too much, we can declare our rejection in the test file, like this:

it('Test if validate the customer externalId', function() {
  let flawedCustomerArgs = [{
    name: 'John',
    details: 'test'
  }]

  ImportService.importCustomer(flawedCustomerArgs)
    .then(result => (...))
    .catch(error => {
       chai
        .assert
        .equal(error, 'Field externalId not defined for Customer')

    })
})
...
Enter fullscreen mode Exit fullscreen mode

But instead i used the chai-as-promised library, that allow us to get rid of writing expectations to promise in the test file and focus only in the result, like this:

const chai = require('chai');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);

it('Test if validate the customer externalId', function() {
  let flawedCustomerArgs = [{
    name: 'John',
    details: 'test'
  }]
  chai
    .expect(ImportService.importCustomer(flawedCustomerArgs))
    .to
    .be
    .rejectedWith('Field externalId not defined for Customer');
})

Enter fullscreen mode Exit fullscreen mode

If you think that there's something confusing, or impacting the understanding, or that i can improve, please i'm going to appreciate your feedback.

See you guys and thanks a lot

Top comments (0)