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)?
Stubs cannot replace attributes, only functions.
The error thrown reinforces this:
From the documentation:
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:
Usage:
You can then in your test write
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()
You need to use
global
to mock thewindow
object for your test inbeforeEach
orit
e.g.
Use
window.location.assign(url)
instead of overwriting the value ofwindow.location
. Then you can just stub theassign
method on thewindow.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.