检查调用 Sinon Stub 的参数是什么?

发布于 2022-09-18 14:01:37 字数 2412 浏览 151 评论 0

有几种方法可以检查在 Sinon 中调用 Stub 的参数是什么,我们推荐的方法是 calledWith() 和相关的助手,以及 getCall()

调用With()

calledWith 如果使用提供的参数至少调用了一次存根,则将返回 true,如果存根函数的参数多于应有的参数,但定位正确,该函数也可以返回 true。

const sinon = require('sinon');

const math = {
  add: (a, b) => { return a + b; }
};

let stub = sinon.stub(math, 'add');

math.add(1, 2);

stub.calledWith(1, 2); // true
stub.calledWith(0, 5); // false

// Reset the stub
sinon.restore();
stub = sinon.stub(math, 'add');

math.add(1, 2, 3, 4, 5); // Called with 3 extra args
stub.calledWith(1, 2); // true, because 1 and 2 are in the same position as the stub call

调用 OnceWith() 和 alwaysCalledWith()

calledOnceWith() 如果 Stub 只被调用一次 并且一个调用的参数使用相同的语义匹配 calledWith()
alwaysCalledWith() 如果每次调用 Stub 时,参数都匹配,则返回 true。

const sinon = require('sinon');

const math = {
  add: (a, b) => { return a + b; }
};

let stub = sinon.stub(math, 'add');

math.add(1,2);
stub.calledOnceWith(1,2); // true

math.add(1,2);
stub.calledOnceWith(1, 2); // false, as add() has been called twice now.
stub.alwaysCalledWith(1, 2); // true

math.add(3, 4);
stub.alwaysCalledWith(1, 2); // false

getCall().args

getCall()函数 返回有关给定调用 Stub 的信息。
getCall(i) 返回一个包含 argsreturnValue 等第 i 次调用 Stub。
getCall() 使用基于 0 的索引,这意味着访问您使用的第一个调用 getCall(0)

const sinon = require('sinon');

const math = {
  add: (a, b) => { return a + b; }
};

let stub = sinon.stub(math, 'add');

math.add(1, 2);
math.add(3, 4);

stub.getCall(0).args; // [1, 2]
stub.getCall(1).args; // [3, 4]

自从 getCall().args 将参数作为 JavaScript 数组返回,然后您可以使用 JavaScript 中比较数组

// Using vanilla JavaScript
function argsEqual(call, arr) {
  return call.args.every((el, i) => el === arr[i]);l
}

argsEqual(stub.getCall(0), [1, 2]); // true
argsEqual(stub.getCall(1), [1, 2]); // false

// Using Node.js' assert lib:
assert.deepEqual(stub.getCall(0).args, [1, 2]);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

终止放荡

暂无简介

文章
评论
662 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文