0

我正在测试一个作为承诺的一部分返回的函数。我正在使用chai-as-promised

我能够测试该功能是否有效,但我无法测试它是否正确抛出错误。

我正在尝试测试的功能,省略了许多与承诺相关的代码:

// function that we're trying to test 
submitTest = (options) => {
  // missingParam is defined elsewhere. It works - the error is thrown if screenshot not passed
  if (missingParam(options.screenShot)) throw new Error('Missing parameter');

  return {};
}

我的测试:

describe('SpectreClient()', function () {
  let client;

  before(() => client = SpectreClient('foo', 'bar', testEndpoint));
  // the client returns a function, submitTest(), as a part of a promise

  /* 
  omitting tests related to the client
  */

  describe('submitTest()', function () {
    let screenShot;
    before(() => {
      screenShot = fs.createReadStream(path.join(__dirname, '/support/test-card.png'));
    });

    // this test works - it passes as expected
    it('should return an object', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({ screenShot });
      });
      return submitTest.should.eventually.to.be.a('object');
    });

    // this test does not work - the error is thrown before the test is evaluated
    it('it throws an error if not passed a screenshot', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({});
      });

      return submitTest.should.eventually.throw(Error, /Missing parameter/);
    });       
  });
})

测试的输出 -

// console output
1 failing

1) SpectreClient() submitTest() it throws an error if not passed a screenshot:
   Error: Missing parameter

如何测试错误是否正确抛出?我不确定这是摩卡咖啡问题还是承诺的事情或 chai-as-promised 的事情。非常感谢帮助。

4

1 回答 1

0

在 Promise 处理程序中引发的异常被转换为 Promise 拒绝。submitTest在回调内部执行client.then,因此它引发的异常变成了一个承诺拒绝。

因此,您应该执行以下操作:

return submitTest.should.be.rejectedWith(Error, /Missing parameter/)
于 2016-11-14T12:11:09.623 回答