Mocha 测试 - 无法使用 async/await 通过对被拒绝承诺的测试

时间:2021-05-18 21:12:21

标签: javascript async-await promise mocha.js chai

使用 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')
  });
});

1 个答案:

答案 0 :(得分:2)

这对我来说非常有效,

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