在Javascript中模拟window.location.href [英] mocking window.location.href in Javascript

查看:138
本文介绍了在Javascript中模拟window.location.href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一个使用window.location.href的函数进行了一些单元测试 - 不太理想我宁愿通过它,但它在实现中是不可能的。我只是想知道是否可以模拟这个值而不会实际导致我的测试运行页面实际上转到URL。

I have some unit tests for a function that makes use of the window.location.href -- not ideal I would far rather have passed this in but its not possible in the implementation. I'm just wondering if its possible to mock this value without actually causing my test runner page to actually go to the URL.

  window.location.href = "http://www.website.com?varName=foo";    
  expect(actions.paramToVar(test_Data)).toEqual("bar"); 

我正在使用jasmine作为我的单元测试框架。

I'm using jasmine for my unit testing framework.

推荐答案

您需要模拟本地上下文并创建自己的窗口窗口。 location objects

You need to simulate local context and create your own version of window and window.location objects

var localContext = {
    "window":{
        location:{
            href: "http://www.website.com?varName=foo"
        }
    }
}

// simulated context
with(localContext){
    console.log(window.location.href);
    // http://www.website.com?varName=foo
}

//actual context
console.log(window.location.href);
// http://www.actual.page.url/...

如果你使用那么所有变量(包括 window !)将首先从上下文对象中查找,如果不存在然后从实际情况来看。

If you use with then all variables (including window!) will firstly be looked from the context object and if not present then from the actual context.

这篇关于在Javascript中模拟window.location.href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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