首页 > 解决方案 > Mocha 测试 - 无法通过使用 async/await 拒绝承诺的测试

问题描述

使用 mocha 和 chai,我试图通过我的第二个测试以获得被拒绝的承诺,但我得到了这个错误Error: the string "error" was thrown, throw an Error

function fn(arg) {
  return new Promise((resolve, reject) => {
    if (arg) {
      resolve('success')
    } else {
      reject('error')
    }
  })
}

describe('Interpreting status', function() {
  it('should return the promise without error', async function(){
    const arg = true
    expect(await fn(arg)).to.equal('success')
  });

  it('should return the promise with an error', async function(){
    const arg = false
    expect(await fn(arg)).to.be.rejectedWith('error')
  });
});

标签: javascriptasync-awaitpromisemocha.jschai

解决方案


这对我来说非常有效,

const chai = require('chai');
const expect = chai.expect;
chai.use(require('chai-as-promised'));

function fn(arg) {
  return new Promise((resolve, reject) => {
    if (arg) {
      resolve('success');
    } else {
      reject(new Error('error'));
    }
  });
}

describe('Interpreting status', function () {
  it('should return the promise without error', async function () {
    const arg = true;
    expect(await fn(arg)).to.equal('success');
  });

  it('should return the promise with an error', async function () {
    const arg = false;
    await expect(fn(arg)).to.be.rejectedWith(Error);
  });
});

第二次测试的问题是,当你这样做时,你await fn(arg)会得到一个错误,而不是你所期望的被拒绝的承诺。
因此,您会看到消息Error: the string "error" was thrown, throw an Error :)
记住,如果您await在一个拒绝的承诺上将抛出一个错误,该错误必须使用try...catch.
所以,如果你想测试,rejectedWith那么不要使用async/await.

此外,每当你执行 Promise 拒绝时,你应该拒绝错误,而不是字符串。我已将拒绝值更改为new Error('error')并且我断言错误类型为rejectedWith

如果您严格按照用例进行,这应该适用于第二次测试,

  it('should return the promise with an error', async function () {
    const arg = false;
    try {
      await fn(arg);
      expect.fail();
    } catch (error) {
      expect(error).to.equal('error');
    }
  });

推荐阅读