首页 > 解决方案 > 为什么这个测试只有在被拒绝时才会失败?

问题描述

该测试通过;即 sinon 说存根实际上是,称为:

const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>yes())
  promise2 = new Promise((yes, no)=>yes())

  Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}  
  await underTest(s)
  sinon.assert.called(s.yes)
}

test().then(console.log('done'))

请注意我没有从Promise.all.

但是,下面的测试会失败,sinon 会说存根没有被调用:

const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>no())
  promise2 = new Promise((yes, no)=>no())

  Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}  
  await underTest(s)
  sinon.assert.called(s.no)
}

test().then(console.log('done'))

如果我返回Promise.all,那么它将通过,并且 sinon 会说s.no存根被调用:

const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>no())
  promise2 = new Promise((yes, no)=>no())

  return Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}  
  await underTest(s)
  sinon.assert.called(s.no)
}

test().then(console.log('done'))

只有当我从Promise.all. 如果我什么都不返回,该async函数将解析为undefined,并且可能会或可能不会调用存根。

我的问题是,如果没有 return 语句,即使是第一种情况,我也会预料到测试会失败,承诺会解决。我本以为诗浓会告诉我s.yes没有被召唤。但是为什么会通过呢?为什么解决和拒绝之间存在不一致?

标签: javascriptnode.jspromisesinon

解决方案


我运行你的代码。否。您的第一个代码/案例测试已完成,但结果未通过。

如果你在运行测试时也实现了 catch ,你就有更好的方法来了解它,如下所示:

test()
.then(() => console.log('done'))
.catch((error) => console.log('Error:', error.message));

您正在不一致地使用异步等待。

如果您使用的是异步等待,则可以使用try 和 catch 捕获错误。

例如:

async function underTest (s){
  promise1 = new Promise((yes, no)=>yes())
  promise2 = new Promise((yes, no)=>yes())

  try {
    await Promise.all([promise1, promise2]);
    s.yes();
  } catch {
    s.no();
  }
  // This will return Promise<void>
}

推荐阅读