如何使用sinon.js监视预定义的对象

How to spy a predefined object with sinon.js

本文关键字:预定义 对象 监视 js 何使用 sinon      更新时间:2023-09-26

我正试图用sinon.js监视window.document。我所做的是:

var document = {
    getElementById = function() {}
}
sinon.spy(document, "getElementById").withArgs("foo").returnValues = ["bar"];

我对这次通话的期望是:当使用参数"foo"调用document.getElementById时,函数必须返回"bar"。我的错误是什么?

如果我自己这样定义getElementById,我会得到预期的结果:

document.getElementById = function(param) {
    if (param === "foo") return "bar";
}

您只能记录对函数的调用并检查是否调用了tey,但永远不能更改函数的行为。来自withArgs:的文档

创建一个仅在收到参数时记录调用的间谍将传递给的与Args 匹配

你要找的码头是sinon.stub:

sinon.stub(document, 'getElementById').withArgs('foo').returns(['bar'])