Verify that an exception is thrown using Mocha / Chai and async/await

后端 未结 11 770
花落未央
花落未央 2020-12-14 05:50

I\'m struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await.

Here\'s an example that works, but I dislike t

相关标签:
11条回答
  • 2020-12-14 06:46
    1. Install chai-as-promised for chai (npm i chai-as-promised -D)
    2. Just call your promise, no await should be applied!
    import chai from 'chai';
    import chaiAsPromised from 'chai-as-promised';
    
    chai.use(chaiAsPromised);
    
    const expect = chai.expect;
    
    describe('MY_DESCR', () => {
      it('MY_TEST', async () => {
        expect(myAsyncFunctionThatWillReject()).to.eventually.be.rejected; 
      });
    });
    
    0 讨论(0)
  • 2020-12-14 06:47

    You can use async/await and should for simple verification

    it('should not throw an error', async () => {
      try {
        let r = await wins();
        r.should.equal('Winner');
      } catch (error) {
        error.should.be.null(); //should.not.exist(error) can also be used
      }
    });
    
    it('throws an error', async () => {
      try {
        await fails();
      } catch (error) {
        error.should.be.Error();
        error.should.have.value("message", "Contrived Error");
      }
    });
    
    0 讨论(0)
  • 2020-12-14 06:47

    you can write a function to swap resolve & reject handler, and do anything normally

    const promise = new Promise((resolve, rejects) => {
        YourPromise.then(rejects, resolve);
    })
    const res = await promise;
    res.should.be.an("error");
    
    0 讨论(0)
  • 2020-12-14 06:52

    A no dependency on anything but Mocha example.

    Throw a known error, catch all errors, and only rethrow the known one.

      it('should throw an error', async () => {
        try {
          await myFunction()
          throw new Error('Expected error')
        } catch (e) {
          if (e.message && e.message === 'Expected error') throw e
        }
      })
    

    If you test for errors often, wrap the code in a custom it function.

    function itThrows(message, handler) {
      it(message, async () => {
        try {
          await handler()
          throw new Error('Expected error')
        } catch (e) {
          if (e.message && e.message === 'Expected error') throw e
        }
      })
    }
    

    Then use it like this:

      itThrows('should throw an error', async () => {
        await myFunction()
      })
    
    0 讨论(0)
  • 2020-12-14 06:53

    I have came with this solution:

    import { assert, expect, use } from "chai";
    import * as chaiAsPromised from "chai-as-promised";
    
    describe("using chaiAsPromised", () => {
        it("throws an error", async () => {
            await expect(await fails()).to.eventually.be.rejected;
        });
    });
    
    0 讨论(0)
提交回复
热议问题