javascript - 为什么这个测试只有在被拒绝时才会失败?
问题描述
该测试通过;即 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
没有被召唤。但是为什么会通过呢?为什么解决和拒绝之间存在不一致?
解决方案
我运行你的代码。否。您的第一个代码/案例测试已完成,但结果未通过。
如果你在运行测试时也实现了 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>
}
推荐阅读
- python - 使用 Keras 进行布尔标签训练会导致错误“请提供具有相同第一维的数据”
- php - 2020 年 11 月 1 日星期日 00:00:00 GMT+0530(印度标准时间)到 PHP 中的 Ymd
- flutter - 周期性计时器有时会延迟并且不会故意抖动
- python - 我可以在 python 中子类化 dict 并避免复制它的数据吗?
- windows - WinSCP同步时删除两边文件
- javascript - 使用不同的回调多次调用 JS 函数每次只执行最后一个回调
- apache-kafka - 在 Kafka 中,如何将 min.insync.replicas=1 设置为 __consumer_offsets_ 主题?
- flutter - Flutter Web:单击时滚动到特定小部件
- ruby - Ruby PG 连接转换错误
- api - GET API 请求以生成新数据