如何在Promise的捕获上对Node单元测试失败?

时间:2016-03-24 19:18:53

标签: javascript node.js unit-testing assert

我正在使用Node.js进行一些单元测试,我希望这样的测试失败:

doSomething()
    .then(...)
    .catch(ex => {
        // I want to make sure the test fails here
    });

我使用Assert,所以我找到了Assert.Fails。问题是fails期望actualexpected,我不会。 Node文档并没有说明需要它们,但Chai documentation符合Node标准,说它们是。

我应该如何对承诺catch的测试失败?

3 个答案:

答案 0 :(得分:3)

您可以使用专用的间谍库,例如Sinon,或者您可以自己实施一个简单的间谍。

href

间谍只是一个包装函数,它记录有关如何调用函数的数据。

function Spy(f) {
  const self = function() {
    self.called = true;
  };
  self.called = false;
  return self;
}

基本原则是监视catch回调,然后使用你的承诺的finally clause来确保没有调用间谍。

答案 1 :(得分:1)

您是否考虑过Assert.Ok(false,message)?它更简洁。

Assert.fail希望进行比较并显示其他信息。

答案 2 :(得分:1)

如果您使用mocha,那么优雅的方式如下:

describe('Test', () => {
  it('first', (done) => {
    doSomething()
    .then(...)
    .catch(done) 
    })
})

如果您的Promise失败,将使用抛出的异常作为参数调用done方法,因此上面的代码等同于

catch(ex => done(ex))

在使用参数的mocha调用done()时,测试失败。