mocking window.location.href in Javascript mocking window.location.href in Javascript javascript javascript

mocking window.location.href in Javascript


The best way to do this is to create a helper function somewhere and then mock that:

 var mynamespace = mynamespace || {};    mynamespace.util = (function() {      function getWindowLocationHRef() {          return window.location.href;      }      return {         getWindowLocationHRef: getWindowLocationHRef      }    })();

Now instead of using window.location.href directly in your code simply use this instead. Then you can replace this method whenever you need to return a mocked value:

mynamespace.util.getWindowLocationHRef = function() {  return "http://mockhost/mockingpath" };

If you want a specific part of the window location such as a query string parameter then create helper methods for that too and keep the parsing out of your main code. Some frameworks such as jasmine have test spies that can not only mock the function to return desired values, but can also verified it was called:

spyOn(mynamespace.util, 'getQueryStringParameterByName').andReturn("desc");//...expect(mynamespace.util.getQueryStringParameterByName).toHaveBeenCalledWith("sort");


I would propose two solutions which have already been hinted at in previous posts here:

  • Create a function around the access, use that in your production code, and stub this with Jasmine in your tests:

    var actions = {    getCurrentURL: function () {        return window.location.href;    },    paramToVar: function (testData) {        ...        var url = getCurrentURL();        ...    }};// Testvar urlSpy = spyOn(actions, "getCurrentURL").andReturn("http://my/fake?param");expect(actions.paramToVar(test_Data)).toEqual("bar");
  • Use a dependency injection and inject a fake in your test:

    var _actions = function (window) {    return {        paramToVar: function (testData) {            ...            var url = window.location.href;            ...        }    };};var actions = _actions(window);// Testvar fakeWindow = {   location: { href: "http://my/fake?param" }};var fakeActions = _actions(fakeWindow);expect(fakeActions.paramToVar(test_Data)).toEqual("bar");


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 contextwith(localContext){    console.log(window.location.href);    // http://www.website.com?varName=foo}//actual contextconsole.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.