编程语言
首页 > 编程语言> > javascript – chai-as-promised:单个测试中的多个expect语句

javascript – chai-as-promised:单个测试中的多个expect语句

作者:互联网

我正在使用chai-as-promised测试一些承诺.我的问题是我不确定如何在一次测试中使用多个期望语句.为了使expect().to.be.fulfilled正常工作,我需要返回它,如下所示:

it('test', () => {
  return expect(promise).to.be.fulfilled
}

…或使用通知,如下所示:

it('test', (done) => {
  expect(promise).to.be.fulfilled.notify(done)
}

问题来自于我需要检查的另一件事,例如调用某个函数,如下所示:

it('test', (done) => {
  var promise = doSomething()
  expect(sinon_function_spy.callCount).to.equal(1)
  expect(promise).to.be.fulfilled.notify(done)
})

这里的问题是,因为doSomething()是异步的,所以当我调用期望时,对sinon_function_spy的调用可能还没有发生,使得这个测试变得不稳定.如果我使用那个,就像这样:

it('test', (done) => {
  var promise = doSomething()
  promise.then(() => {
    expect(sinon_function_spy.callCount).to.equal(1)
  })
  expect(promise).to.be.fulfilled.notify(done)
})

然后测试在技术上通过并按预期失败,但它将失败,因为promise被拒绝,因为在then调用中抛出异常.同样,如果我有一个承诺预计拒绝的情况:

it('test', (done) => {
  var promise = doSomething()
  promise.then(() => {
    expect(sinon_function_spy.callCount).to.equal(1)
  })
  expect(promise).to.be.rejected.notify(done)
})

然后对sinon_function_spy的检查永远不会被调用,因为promise被拒绝了,然后没有调用.

如何让两个expect语句可靠地执行并返回正确的值?

解决方法:

如果想要断言Promise已经完成并且调用是按预期执行的,那么您并不需要将第一部分作为断言.如果Promise拒绝,只要你返回它,mocha测试用例本身就会失败:

it('test', () => {
  return doSomething()
    .then(() => {
      expect(sinon_function_spy.callCount).to.equal(1)
    });
});

如果doSomething()返回的Promise拒绝,那么测试用例也是如此.如果期望断言失败,那么失败的断言也会使测试用例失败.如果你想更明确一点:

it('test', () => {
  return doSomething()
    .then(() => {
      expect(sinon_function_spy.callCount).to.equal(1)
    }, err => {
      expect(err).to.not.exist;
    });
});

……你可以发现错误.请注意,有了这个带有两个回调的味道,第一个回调中的断言失败将不会到达第二个回调,所以它只是Mocha看到失败的断言.

以下是您可以做出预期失败的承诺的方法:

it('test', () => {
  return doSomething()
    .then(() => {
      throw new Error('Promise should not have resolved');
    }, err => {
      expect(err).to.exist;
      expect(sinon_function_spy.callCount).to.equal(1)
    });
})

标签:javascript,node-js,mocha,chai,chai-as-promised
来源: https://codeday.me/bug/20190522/1153383.html