Search code examples
javascriptmockingjasmine

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";    
  expect(actions.paramToVar(test_Data)).toEqual("bar"); 

I'm using jasmine for my unit testing framework.


Solution

  • 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/...
    

    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.