Stubbing window.location.href with Sinon

Francesco Pezzella picture Francesco Pezzella · Apr 17, 2016 · Viewed 30.5k times · Source

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

describe('Logger', () => {
    it('should compose a Log', () => {
        var stub = sinon.stub(window.location, 'href', 'http://www.foo.com');
    });
});

The runner displays the following error:

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

Changing the test code to:

describe('Logger', () => {
    it('should compose a Log', () => {
        var stub = sinon.stub(window.location, 'href', {
            value: 'foo'
        });
    });
});

Which yields this error:

TypeError: Attempted to wrap string property href as function

Passing a function as third argument to sinon.stub doesn't work either.

Is there a way to provide a fake window.location.href string, also avoiding redirection (since I'm testing in the browser)?

Answer

KhaledMohamedP picture KhaledMohamedP · Feb 10, 2017

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