在qUnit中测试整个页面重定向 [英] Testing a whole page redirect in qUnit

查看:98
本文介绍了在qUnit中测试整个页面重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能

var redirect = function() {
    window.location.href = "http://www.google.com";
}

我想使用qUnit测试此功能.

I want to test this function using qUnit.

问题是,当我调用运行测试的HTML文档时,只要它到达调用redirect()的测试,浏览器就会加载google.com.我想做的是以某种方式模拟window.location.href,以便它不会重定向,因此我可以检查它是否设置为正确的值.

The problem is, when I call up the HTML document in which my tests run, as soon as it gets to the test that calls redirect(), the browser loads google.com. What I would like to do is mock out window.location.href somehow so that it doesn't redirect, and so I can check that it was set to the proper value.

以一种更具可测试性的方式重写此内容将是一个可以接受的答案,因此受到欢迎.由于我使用的是qUnit,因此一些jQuery魔术将是适当的,一些老式的重构也将是适当的.建议为window.location.href添加一个自定义设置器,但是我不知道如何使它工作.

Rewriting this in a manner that it would be more testable would be an acceptable answer and is welcomed. Since I am using qUnit, some jQuery magic would be appropriate, as would some old fashioned refactoring. Adding a custom setter for window.location.href was suggested, but I couldn't figure out how to get this to work.

请,没有建议更改我的代码的行为.

Please, no suggestions of changing the behavior of my code.

推荐答案

这就是我最终解决它的方式. giggity.navOnChange是与原始问题中的redirect类似的功能.

Here's how I ended up solving it. giggity.navOnChange is the function analogous to redirect in the original question.

代码:

var giggity = giggity || {};

$(document).ready(function() {
    $("#branches").change(giggity.navOnChange);
    $("#tags").change(giggity.navOnChange);
});

giggity.window = window;

giggity.navOnChange = function() {
    giggity.window.location.href = this.value;
};

测试代码:

var giggity = giggity || {};

test("giggity.navOnChange", function() {
    var temp = giggity.window
    giggity.window = { location: {} };
    var mockSelect = {
        value: "/link/to/some/branch",
        onChange: giggity.navOnChange
    }
    mockSelect.onChange();
    equal(giggity.window.location.href, mockSelect.value);
    giggity.window = temp; // restore mocked variable
});

我正在使用giggity对象作为代码的命名空间.我将giggity.window变量分配为指向window,并通过giggity.windowwindow进行交互.这样,我可以轻松地模拟出window对象的任何操作.我将giggity.window指向模拟对象,调用修改giggity.window的函数并检查模拟值.

I'm using the giggity object as a namespace for my code. I assign the giggity.window variable to point to window, and interact with window via giggity.window. This way, I can easily mock out any manipulation of the window object. I point giggity.window to a mock object, call the function that modifies giggity.window and check the value of the mock.

这篇关于在qUnit中测试整个页面重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆