Skip to content Skip to sidebar Skip to footer

Stubbing Window.location.href With Sinon

I am trying to test some client-side code and for that I need to stub the value of window.location.href property using Mocha/Sinon. What I have tried so far (using this example): d

Solution 1:

You need to use global to mock the window object for your test in beforeEach or it

e.g.

it('should compose a Log', () => {
   global.window = {
       location: {
           href: {
               value: 'foo'
           }
       }
   }
  //.... call the funciton 
});

Solution 2:

Stubs cannot replace attributes, only functions.

The error thrown reinforces this:

TypeError: Custom stub should be a function or a property descriptor

From the documentation:

When to use stubs?

Use a stub when you want to:

  1. Control a method’s behavior from a test to force the code down a specific path. Examples include forcing a method to throw an error in order to test error handling.

  2. When you want to prevent a specific method from being called directly (possibly because it triggers undesired behavior, such as a XMLHttpRequest or similar).

http://sinonjs.org/releases/v2.0.0/stubs/


Possible solution

While many builtin objects can be replaced (for testing) some can't. For those attributes you could create facade objects which you then have to use in your code and being able to replace them in tests.

For example:

var loc = {

    setLocationHref: function(newHref) {
        window.location.href = newHref;
    },

    getLocationHref: function() {
        returnwindow.location.href;
    }

};

Usage:

loc.setLocationHref('http://acme.com');

You can then in your test write

var stub = sinon.stub(loc, 'setLocationHref').returns('http://www.foo.com');

Note the chained returns() call. There was another error in your code: the third argument has to be a function, not value on another type. It's a callback, not what the attribute should return.

See the source code of stub()

Solution 3:

Use window.location.assign(url) instead of overwriting the value of window.location. Then you can just stub the assign method on the window.location object.

http://www.w3schools.com/jsref/met_loc_assign.asp


UPDATE: I tested this in a headless browser, but it may not work if you run your tests in Chrome. See @try-catch-finally's response.

Post a Comment for "Stubbing Window.location.href With Sinon"