I'm writing a library that supports browser navigation with the help of history.pushState and also catches the popstate event that communicates when navigation takes place in the browser. As I'm trying to write Jasmine tests for this library, I'm wondering how I can mock history.pushState
and also fake the emission of the popstate
signal from window
? The following code snippets should elucidate the problem:
Library code:
var lib = (function() {
function navigate(path) {
history.pushState(null, null, path);
}
function onPopState(event) {
if (lib.callback) {
lib.callback(document.location);
}
}
$(window).bind('popstate', onPopState);
return {
navigate: navigate
};
})();
Test code (Jasmine):
describe("Test navigate", function() {
it("Should invoke callback upon state change", function() {
var invokedWith;
function callback(url) {
invokedWith = url;
}
lib.callback = callback;
lib.navigate('/path');
// Doesn't work, callback invoked asynchronously
expect(invokedWith).toEqual('/path');
});
});
Basically, I want to mock the history.pushState
function and emit a fake popstate
event from window
, so as to test the popstate
handling in lib
.
See also my fiddle for "working" code.
But this function is not intended to reload the browser. All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
replaceState() The History. replaceState() method modifies the current history entry, replacing it with the state object and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
You can spy on history.pushState
like this:
spyOn(history, 'pushState');
As you use jquery to bind the event you can simply trigger popstate
by yourself.
$(window).trigger('popstate')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With