【问题标题】:testing a function that has been returned by a promise - checking for errors测试一个由 promise 返回的函数 - 检查错误
【发布时间】:2017-03-26 13:08:18
【问题描述】:

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

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

我正在尝试测试的函数,省略了很多与 promise 相关的代码:

// 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 的事情。非常感谢帮助。

【问题讨论】:

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


    【解决方案1】:

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

    所以你应该这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2021-06-23
      • 2015-02-24
      • 2020-06-20
      • 2021-10-18
      • 1970-01-01
      • 2017-09-13
      相关资源
      最近更新 更多