【问题标题】:Jasmine testing the postMessage APIJasmine 测试 postMessage API
【发布时间】:2014-04-16 13:35:55
【问题描述】:

我正在尝试在我的脚本中测试异步 postMessage API,该脚本在真实浏览器中运行良好,但为其创建测试相当复杂。 为了说明这个案例,我编写了这个简化的测试案例:

describe('calling postMessage asynchronously', function () {
    var ctx;
    beforeEach(function () {
        jasmine.clock().install();
        ctx = {
            msgHandler:function() {
                console.log('msgHandler');
            }
        };
    });
    afterEach(function () {
        jasmine.clock().uninstall();
    });
    it('handles a postMessage asynchronously', function() {
        window.addEventListener('message', ctx.msgHandler);
        spyOnEvent('window', 'message');
        spyOn(ctx, 'msgHandler');
        setTimeout(function() {
            window.postMessage('another bam', '*');
        }, 10);
        jasmine.clock().tick(11);
        expect(ctx.msgHandler).toHaveBeenCalled();
    });
});

现在为什么没有调用消息处理程序?

【问题讨论】:

    标签: javascript unit-testing asynchronous jasmine


    【解决方案1】:
    describe('window.postMessage test', function() {
        var o;
        beforeEach(function(done) {
            o = {
                f: function() {
                    o.f2();
                },
                f2: function() {}
            };
            window.addEventListener('message', o.f, false);
            spyOn(o, 'f2').and.callFake(function() {
                done();
            });
            window.postMessage('another bam', '*');
        });
        it('works...', function() {
            expect(o.f2).toHaveBeenCalled();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2016-02-14
      相关资源
      最近更新 更多