使用Sinon对window.location.href进行存根 [英] Stubbing window.location.href with Sinon
问题描述
我正在尝试测试一些客户端代码,为此我需要使用Mocha / Sinon存储 window.location.href
属性的值。
I am trying to test some client-side code and for that I need to stub the value of window.location.href
property using Mocha/Sinon.
到目前为止我所尝试的内容(使用此示例):
What I have tried so far (using this example):
describe('Logger', () => {
it('should compose a Log', () => {
var stub = sinon.stub(window.location, 'href', 'http://www.foo.com');
});
});
跑步者显示以下错误:
TypeError:自定义存根应该是函数或属性描述符
TypeError: Custom stub should be a function or a property descriptor
将测试代码更改为:
describe('Logger', () => {
it('should compose a Log', () => {
var stub = sinon.stub(window.location, 'href', {
value: 'foo'
});
});
});
产生此错误:
TypeError:尝试将字符串属性href包装为函数
TypeError: Attempted to wrap string property href as function
将函数作为第三个参数传递给 sinon.stub
也不起作用。
Passing a function as third argument to sinon.stub
doesn't work either.
有没有办法提供假的 window.location .href
字符串,也避免重定向(因为我在浏览器中测试)?
Is there a way to provide a fake window.location.href
string, also avoiding redirection (since I'm testing in the browser)?
推荐答案
Stubs不能替换属性,只能替换函数。
Stubs cannot replace attributes, only functions.
抛出的错误强化了这一点:
The error thrown reinforces this:
TypeError:自定义存根应该是函数或属性描述符
TypeError: Custom stub should be a function or a property descriptor
来自文档:
何时使用存根?
When to use stubs?
如果您想要使用存根:
-
从测试中控制方法的行为以强制代码沿特定路径下移。示例包括强制方法抛出错误以测试错误处理。
Control a method’s behavior from a test to force the code down a specific path. Examples include forcing a method to throw an error in order to test error handling.
当您想要阻止直接调用特定方法时(可能因为它触发不受欢迎的行为,例如XMLHttpRequest或类似行为。
When you want to prevent a specific method from being called directly (possibly because it triggers undesired behavior, such as a XMLHttpRequest or similar).
http://sinonjs.org/releases/v2.0.0/stubs/
虽然可以替换许多内置对象(用于测试)有些人不能。对于这些属性,您可以创建外观对象,然后必须在代码中使用它们并且能够在测试中替换它们。
While many builtin objects can be replaced (for testing) some can't. For those attributes you could create facade objects which you then have to use in your code and being able to replace them in tests.
例如:
var loc = {
setLocationHref: function(newHref) {
window.location.href = newHref;
},
getLocationHref: function() {
return window.location.href;
}
};
用法:
loc.setLocationHref('http://acme.com');
您可以在测试中写一下
var stub = sinon.stub(loc, 'setLocationHref').returns('http://www.foo.com');
注意链式返回()
调用。您的代码中还有另一个错误:第三个参数必须是函数,而不是另一个类型的值。这是一个回调,而不是该属性应返回的内容。
Note the chained returns()
call. There was another error in your code: the third argument has to be a function, not value on another type. It's a callback, not what the attribute should return.
这篇关于使用Sinon对window.location.href进行存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!