9

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?

Fede E.
  • 2,118
  • 4
  • 23
  • 39

1 Answers1

21

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);
    }
  });
});
lleon
  • 2,615
  • 1
  • 20
  • 14
  • Ah! I was looking at that lib right when I got your answer. Worth mentioning that in my case, inside rejectedWith(), it should have the rejection reason. Thanks! – Fede E. May 18 '18 at 13:43