mocking window.location.href in Javascript

mock window.location.href angular
mock window.location.href jasmine angular
angular 2 test window location: ( href)
how to override window location href
sinon window location: ( href)
error: not implemented: navigation (except hash changes)
mock document location href
mock window jest

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

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

// simulated context

//actual context

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.

How to mock window.location.href with Jest + Vuejs?, You can try: global.window = Object.create(window); const url = "http://dummy. com"; Object.defineProperty(window, 'location', { value: { href: url }� There may be a situation where you need to mock methods or properties on window.location in Jest. However, because of peculiarities of jsdom, this could be challenging. In this post there is one of the possible solutions to this problem.

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

Jest: How to Mock window.location.href — Wild Wild Wolf, = url;. }, 1500) JavaScript. Object. One of the solutions was to redefine window object completely, and then use Object. window.location.href returns the href (URL) of the current page; window.location.hostname returns the domain name of the web host; window.location.pathname returns the path and filename of the current page; window.location.protocol returns the web protocol used (http: or https:) window.location.assign() loads a new document

Jest: mock window.location methods, js. Mock method�. To remove the error, location.reload needs to be made configurable before being assigned to a mock:. window.location is mocked with an object with the same API (members like.href, but setting location.href will just do nothing. Still reading from location.href will return the value that was previously set, so you can run assertions against that value to check if you app tried to redirect to the expected URL.

Sometimes you may have a library that modifies window.location and you want to allow for it to function normally but also be tested. If this is the case, you can use a closure to pass your desired reference to your library such as this.

/* in mylib.js */
    view.location.href = "foo";
}(self || window));

Then in your test, before including your library, you can redefine self globally, and the library will use the mock self as the view.

var self = {
   location: { href: location.href }

In your library, you can also do something like the following, so you may redefine self at any point in the test:

/* in mylib.js */
var mylib = (function(href) {
    function go ( href ) {
       var view = self || window;
       view.location.href = href;
    return {go: go}

In most if not all modern browsers, self is already a reference to window by default. In platforms that implement the Worker API, within a Worker self is a reference to the global scope. In node.js both self and window are not defined, so if you want you can also do this:

self || window || global

This may change if node.js really does implement the Worker API.

How to mock window.location.href � Issue #10 � ShirlyChenLaLaLa , js . However, we cannot change url on the fly outside of unit test code whether it is using window.location.href or other ways such as� @jam3sn_codes: This is awesome, I’ve used window.location.href in the past, but didn’t realise how simple it is to access sections of the URL! If you want to see a live-action of what James is talking about, check out the table of content at the top of this article. Click on it and it will scroll down to the specific section of the page.

Below is the approach I have take to mock window.location.href and/or anything else which maybe on a global object.

First, rather than accessing it directly, encapsulate it in a module where the object is kept with a getter and setter. Below is my example. I am using require, but that is not necessary here.

define(["exports"], function(exports){

  var win = window;

  exports.getWindow = function(){
    return win;

  exports.setWindow = function(x){
    win = x;


Now, where you have normally done in your code something like window.location.href, now you would do something like:

var window = global_window.getWindow();
var hrefString = window.location.href;

Finally the setup is complete and you can test your code by replacing the window object with a fake object you want to be in its place instead.

fakeWindow = {
  location: {
    href: ""
w = require("helpers/global_window");

This would change the win variable in the window module. It was originally set to the global window object, but it is not set to the fake window object you put in. So now after you replaced it, the code will get your fake window object and its fake href you had put it.

window.location.href can't be changed in tests. � Issue #890 , lib/window', window) jest.mock('cookies-js') jest.mock('query-string') window. location.href= with window.location.assign and mock assign� How to mock a window.location function in Karma/jasmine Tag: angularjs , unit-testing , karma-jasmine I would like to mock a functionality in Karma who returns a file after clicking a download button.

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� var window = global_window. getWindow (); var hrefString = window. location. href; Finally the setup is complete and you can test your code by replacing the window object with a fake object you want to be in its place instead.

jasmine + karma test runner: how to test window.location.href, jasmine + karma test runner: how to test window.location.href - angular. Window is an object like any other. you should be able to mock it in your tests like so Do I have to also add location to the global variable in jest-environment.js file? mocking window.location.href nel Javascript Ho alcuni test di unità per una function che utilizza la window.location.href – non è ideale che avrei preferito passarlo piuttosto ma non è ansible nell'implementazione.

How to mock window.location.href with Jest + Vuejs?, defineProperty(window.location, "href", { value: url, writable: true }); const data = { id: Jest: mock window.location methods, Using our favorite JavaScript testing� Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

  • I having the same problem when I want to call a function within the with. How do you solve it?
  • 'with' statements are not allowed in strict mode.
  • Does not look to me like you can write readable tests with it. I think the solution proposed by @Kurt Harriger is way better. -1
  • The with(obj) {} statement is deprecated, and as such, is not valid in strict mode.
  • In Jasmine 2.x the syntax used in the first example appears to have changed a little. .andReturn() should be replaced by .and.returnValue().
  • only works for jest, not for karma (cannot delete property location)
  • If using TS you could try this: delete (<any>window).location;
  • doesn't work either at runtime, I ended up creating a private method to return the pathname and spying it with spyOn(component, "getLocationPathname").and.returnValue("/someroute"); with a // @ts-ignore to ignore the private.