测试promise承诺返回的函数 - 检查错误

时间:2016-11-12 11:57:53

标签: javascript mocha chai es6-promise chai-as-promised

我正在测试一个作为promise的一部分返回的函数。我正在使用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

如何测试错误是否被抛出?我不确定它是摩卡问题还是承诺的事情或者是承诺的事情。非常感谢。

1 个答案:

答案 0 :(得分:0)

承诺处理程序中引发的异常转换为承诺拒绝。 submitTestclient.then的回调中执行,因此它引发的异常成为拒绝承诺。

所以你应该这样做:

return submitTest.should.be.rejectedWith(Error, /Missing parameter/)