sinon的stub.yields有什么作用?
What does sinon's stub.yields do?
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
的示例(文档没有提供)。
如果您存根的函数需要回调,例如异步数据库请求,这允许存根伪造函数通常传递给您的回调的结果。
举个例子可能更容易:
// 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 */}
您可以通过针对您的代码生成不同的值和 运行 断言来模拟来自数据库的各种结果。
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
的示例(文档没有提供)。
如果您存根的函数需要回调,例如异步数据库请求,这允许存根伪造函数通常传递给您的回调的结果。
举个例子可能更容易:
// 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 */}
您可以通过针对您的代码生成不同的值和 运行 断言来模拟来自数据库的各种结果。