gpt4 book ai didi

javascript - sinon 的 stub.yields 有什么作用?

转载 作者:行者123 更新时间:2023-11-29 10:56:06 27 4
gpt4 key购买 nike

sinon 的文档说 stub.yields 这样做:

stub.yields([arg1, arg2, ...]) Similar to callsArg.

Causes the stub to call the first callback it receives with the provided arguments (if any).

If a method accepts more than one callback, you need to use yieldsRight to call the last callback or callsArg to have the stub invoke other callbacks than the first or last one.

我读了好几遍,但无法理解它想表达的意思。我发现粗体部分特别令人困惑。

对我有帮助的是一个比这个更详细的解释和一个或两个展示如何使用 yields 的例子(文档没有提供)。

最佳答案

如果您 stub 的函数接受回调,例如异步数据库请求,这允许 stub 伪造函数通常传递给您的回调的结果。

举个例子可能更容易:

// simulated db api
let db = {
get(query, cb) {
cb(null, "your results from the query")
}
}

function runQuery(q) {
db.get(q, (err, val) => {
if (err) console.log("error!", err)
else console.log("value:", val)
})
}
// call it normally
runQuery("some query")

// stub the DB get method
let stub = sinon.stub(db, 'get');

// fake query results
stub.yields(null, "results from Sinon Stub")

// now stubbed
runQuery("some query")
// assert that `runQuery` did what it should
// given a value of `results from Sinon Stub`
// from db.get

// see how it handles an error:
stub.yields("Some error")

runQuery("some query")
// assert that `runQuery` did what it should
// when db errors with "Some error"
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.3.2/sinon.min.js"></script>

如果你有一个接受回调的异步函数并且你想用各种结果测试它——例如,如果你有一个用回调调用的数据库函数:

db.get("someVal", (err, val) => {/* do something */}

您可以通过生成不同的值并针对您的代码运行断言来模拟来自数据库的各种结果。

关于javascript - sinon 的 stub.yields 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961294/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com