这是我的代码:
var getCode = function(code) {
if (code = (new RegExp('[?&]' + encodeURIComponent(code) + '=([^&]*)'))
.exec(location.search))
return decodeURIComponent(code[1]);
};
$(document).ready(function() {
var code = getCode("code");
//some other function
这是我的测试代码:
it("check the code value of url", function() {
window.location.search = "https://test.com?&code=testParam";
var code = getCode("code");
expect(code).toEqual("testParam");
});
每当我尝试将其作为 jasmine 测试运行时,它都会显示 runtimeexception 或说 hte 变量 getCode 未定义。无论如何我可以设置位置 url 并测试它吗?
非常感谢您的帮助
最佳答案
我认为你应该做些不同的事情。 不要从浏览器中获取 url。而是将 url 作为参数传递给函数。这样您就可以硬编码 url 并将其发送给测试。
var getCode = function(code, url) {
if (code = (new RegExp('[?&]' + encodeURIComponent(code) + '=([^&]*)'))
.exec(url))
return decodeURIComponent(code[1]);
};
然后像下面这样运行测试。
it("check the code value of url", function() {
var url = "https://test.com?&code=testParam";
var code = getCode("code", url);
expect(code).toEqual("testParam");
});
希望对您有所帮助。
关于javascript - Jasmine 测试 url 的 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481390/