wmitchell wmitchell - 5 months ago 66
Javascript Question

mocking window.location.href in Javascript

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";

I'm using jasmine for my unit testing framework.


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

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

// simulated context
    // http://www.website.com?varName=foo

//actual context
// http://www.actual.page.url/...

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.