Jasmine - 我如何模拟history.pushState以及假事件发射?

akn*_*ds1 6 javascript testing jquery mocking jasmine

我正在编写一个在history.pushState的帮助下支持浏览器导航的库,并且还捕获在浏览器中进行导航时进行通信的popstate事件.当我正在尝试为这个库编写Jasmine测试时,我想知道我如何模拟history.pushState并伪造popstate信号的发射来自window?以下代码片段应该阐明问题:

图书馆代码:

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
    };
})();
Run Code Online (Sandbox Code Playgroud)

测试代码(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');
    });
});
Run Code Online (Sandbox Code Playgroud)

基本上,我想模拟history.pushState函数并popstate从中发出假事件window,以便测试popstate处理lib.

另见"工作"代码的小提琴.

And*_*rle 4

history.pushState你可以这样监视:

spyOn(history, 'pushState');
Run Code Online (Sandbox Code Playgroud)

当你使用jquery绑定事件时,你可以简单地popstate自己触发。

$(window).trigger('popstate')
Run Code Online (Sandbox Code Playgroud)