Fede E.
Fede E.

Reputation: 1918

Using Chai expect throw not catching promise rejection

I have searched all around how to solve this, but all solutions I tested don't work in my case.

I have a function that returns a promise, which I'm trying to test using Mocha and Chai.

I'm fuzzing the parameter so the function always returns:

reject('Rejection reason')

Here's the test I'm trying to run:

describe('fuzzing tokenization with 1000 invalid values', () => {

   it('should throw an error - invalid value', async () => {

      for(var i=0; i <= 1000; i++){

          var req = {
              body: {
                  value: fuzzer.mutate.string('1000000000000000')
              },
              user: {
                  displayName: user
              }
          };

          expect(await tokenizer.tokenize(req)).to.throw(Error);

      }

   });

});

The test is failing with:

Error: the string "Invalid value." was thrown, throw an Error :)

I tested several changes like wrapping the expect into a function

expect(async () => { ...}).to.throw(Error);

and others I found googling. But I can't get this to work.

What am I missing?

Upvotes: 9

Views: 11306

Answers (1)

lleon
lleon

Reputation: 2765

expect().to.throw(Error) will only work for sync functions. If you want a similar feature using async functions take a look at chai-as-promised

import chaiAsPromised from 'chai-as-promised';
import chai from 'chai';

chai.use(chaiAsPromised)
var expect = chai.expect;

describe('fuzzing tokenization with 1000 invalid values', () => {
  it('should throw an error - invalid value', async () => {
    for (var i = 0; i <= 1000; i++) {
      var req = {
        body: {
          value: fuzzer.mutate.string('1000000000000000')
        },
        user: {
          displayName: user
        }
      };

      await expect(tokenizer.tokenize(req)).to.eventually.be.rejectedWith(Error);
    }
  });
});

Upvotes: 21

Related Questions