Home > Blockchain >  How to test for error thrown using chai or chai-as-promised for async functions?
How to test for error thrown using chai or chai-as-promised for async functions?

Time:09-16

I have a function as follows:

async foo() : Promise<Object> { 
   if(...) throw new Error
}

How am I supposed to test that the error is thrown? Currently I'm doing this:

it("testing for error thrown", async function () {
   expect(async() => await foo()).to.throw(Error)
})

CodePudding user response:

You can do something like this and if the error is thrown, the test will fail.

const foo = async (): Promise<Object> => {
  // If you want the test to fail increase x to 11
  const x = 0
  if (x > 10) {
    throw Error('Test will fail')
  }
  // Add meaningful code this is just an example
  return { some: 'object' }
}

it('testing for error thrown', async () => {
  const object = await foo()
  expect(object).toEqual({ some: 'object' })
})

CodePudding user response:

Try this:

it("testing for error thrown", async function () {
   await expect(foo()).rejects.toThrow(Error)
})

CodePudding user response:

Since you mentioned chai-as-promised, you would use either:

expect(promise).to.eventually.be.rejected

or:

promise.should.be.rejected

There's also rejectedWith() which lets you specify the Error class/constructor.

Here's a demo:

mocha.setup('bdd');
mocha.checkLeaks();

let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* hack due to lack of UMD file, only for SO */
chai.use(chaiAsPromised);

async function foo(){ 
   throw new Error();
}

describe('Asynchronous Function', function(){
  it('Expect and Eventually', function(){
      return expect(foo()).to.eventually.be.rejected;
  })
  
  it('With Should', function(){
      return foo().should.be.rejected;
  });
});

mocha.run();
.as-console {
   display: none !important;
}
<script>
window.module = {}; function require(){ return {} }; /* hack due to lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/[email protected]/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>

  • Related