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

后端 未结 11 852
花落未央
花落未央 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:37

    If test your Promised function, in the test must wrap the code inside a try/catch and the expect() must be inside the catch error block

    const loserFunc = function(...args) {
      return new Promise((resolve, rejected) => {
        // some code
        return rejected('fail because...');
      });
    };
    

    So, then in your test

    it('it should failt to loserFunc', async function() {
      try {
        await loserFunc(param1, param2, ...);
      } catch(e) {
        expect(e).to.be.a('string');
        expect(e).to.be.equals('fail because...');
      }
    });
    

    That is my approach, don't know a better way.

提交回复
热议问题