javascript - Jasmine 测试 url 的 javascript 函数

标签 javascript url testing jasmine

这是我的代码:

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/

相关文章:

java - 无法从 src\test 文件夹中找到 "Run File"-> 找不到或无法加载主类

javascript - 外部JS : Can't validate form

javascript - Node.js 它打印相同的结果两次,而不是一次

javascript - Backbone 全局模型

javascript - 用 Jest 模拟 ES6 类函数

ruby-on-rails - 根据 current_user - ROR 更改 url

ios - 自定义 URL 方案 RubyMotion

testing - 在不使用标题的情况下选择 Selenium 中的窗口

用于 Web 浏览器的 Python URL 处理程序

testing - 重复 "Asynchronous Sessions cleanup phase starting NOW"