1

I have a snippet of code that I'm testing in Chai and Pact. It looks something like this:

      var myVerify = () => {
        provider.verify().then(() => {
          console.log('B verified')
          done()
        })
      }
      expect(myVerify).to.not.throw()

This works but it's a lot of extra work to go through to make a wrapper function to ensure that I wait on Pact's verify complete's before continuing on with the test. Pact has some internal state that will clear when it's done. If I just call this:

expect(provider.verify()).to.not.throw()

then it will conflict with other tests.

This code seems to work fine for me but it's very messy. Its there a simpler way to accomplish this?

4

1 回答 1

1

我不会推荐这种方法,因为如果确实发生了错误,那么无论如何它都不会被捕获,因为承诺不会“抛出错误”,它们只是拒绝承诺,您可以使用.catch或作为第二个参数来捕获它.then.

有两种方法可以做你想做的事:

1)只有摩卡:

return provider.verify().then(() => {
      console.log('B verified');
      done();
}, () => throw new Error("B verification failed"));

在这个简单的例子中,我们没有使用 chai 来验证任何东西,因为您实际上并没有验证 verify 的数据输出,您只是检查 promise 是否成功,如果没有,则抛出一个错误,这将使您失败测试。默认情况下,Mocha 理解承诺,只要它们作为测试的一部分返回。

但是,这种方法意味着包装it函数需要注入done参数,我不喜欢这个。我喜欢的是使用:

2) Chai with Chai as Promised :

您需要按照承诺设置 chai 使用

chai.use(require("chai-as-promised))

然后在您的测试中,只需执行以下操作:

return expect(provider.verify()).to.eventually.be.fulfilled;

该测试将等待 promise 返回,chai 将验证它实际上是否已实现且未被拒绝。我发现这种语法使用起来更简单,并且使编写测试更简单。您还可以使用相同的承诺有多个期望Promises.all

var verify = provider.verify();
return Promises.all(
    expect(verify).to.eventually.be.fulfilled,
    expect(verify).to.eventually.be.true,
);
于 2017-10-16T23:24:41.037 回答