Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine - How can I mock history.pushState and also fake event emission?

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.

like image 276
aknuds1 Avatar asked Jan 01 '13 13:01

aknuds1


People also ask

Does history pushState reload page?

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.

What is window history replaceState?

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.


1 Answers

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')
like image 146
Andreas Köberle Avatar answered Oct 23 '22 06:10

Andreas Köberle