Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 347
wmitchell Avatar asked Jan 25 '11 10:01

wmitchell


People also ask

How do you set a Windows href location?

href = "https://www.example.com"; // Assigns a new URL to the current window. window. location. assign("https://www.example.com"); // Replaces the location of the current window with the new one.

What is window location href?

Window Location Href The window.location.href property returns the URL of the current page.


1 Answers

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"); 
like image 116
Kurt Harriger Avatar answered Oct 06 '22 18:10

Kurt Harriger