您无法在不重新加载页面的情况下修改 window.location.href。但是,如果您绝对想测试这些功能,则需要进行一些逻辑修改。
示例 #1:
您可以使用两个函数来完成此操作,一个可以是与您的类似的简单 redirectTo 函数,另一个可以是具有构建和 url 逻辑的函数。像这样:
// this function is so simple that you never need to unit test it
var redirectTo = function(url)
{
window.location.href = url;
}
// if this function has any logic worth testing you can do that without redirects
var buildUrl = function(someParameters)
{
// ....
// here be some logic...
// ....
return "http://www.google.com";
}
- redirectTo(url) 函数非常简单,您将始终知道它无需测试即可工作。
- buildUrl(someParameters) 函数可以包含构建 URL 的逻辑,您应该对此进行测试。您可以在没有页面重定向的情况下对此进行测试。
示例 #2:
您还可以在这两者之间写一个交叉:
// don't test this function as it will redirect
var redirect = function()
{
window.location.href = buildUrl();
}
// if this function has any logic worth testing you can do that without redirects
var buildUrl = function()
{
// ....
// here be some logic...
// ....
return "http://www.google.com";
}
上面的示例将具有与您的原始函数类似的形式,但具有您可以实际测试的 URL 构建逻辑函数。
不是一个例子,而是#3:
另一方面,如果你不想改变你的逻辑并且你有一个简单的功能,如果你不测试它就没什么大不了的......