Using Chai expect throw not catching promise rejection

痞子三分冷 提交于 2020-12-06 04:50:09

问题


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?


回答1:


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);
    }
  });
});


来源:https://stackoverflow.com/questions/50412182/using-chai-expect-throw-not-catching-promise-rejection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!