【问题标题】:Testing window.postMessage directive测试 window.postMessage 指令
【发布时间】:2015-06-19 13:35:48
【问题描述】:

我在测试通过注册消息处理程序启用跨文档消息传递的指令时遇到问题:

.directive('messaging', function ($window, MyService) {
    return {
        link: function () {
            angular.element($window).on('message', MyService.handleMessage);
        }
    };
})

我只想进行单元测试,当编译该指令并调用window.postMessage('message','*') 时,应该调用我的消息处理程序:

http://jsfiddle.net/mhu23/L27wqn14/(含茉莉测试)

非常感谢您的帮助! 迈克尔

【问题讨论】:

    标签: angularjs angularjs-directive jasmine


    【解决方案1】:

    您正在使用原始的window API,您没有在模拟它,因此postMessage 方法将保持它的异步行为。知道这一点,测试应该以异步方式编写。在 JSFiddle 你有 Jasmine 1.3,所以测试应该看起来像这样:

    it('should ....', function () {
    
        var done = false;
    
        spyOn(MyService,'handleMessage').andCallFake(function () {
            // set the flag, let Jasmine know when callback was called
            done = true; 
        });
    
        runs(function () {
            // trigger async call
            $window.postMessage('message','*');    
        });
    
        waitsFor(function () {
            // Jasmine waits until done becomes true i.e. when callback be called
            return done; 
        });
    
        runs(function () {
            expect(MyService.handleMessage).toHaveBeenCalled();
        });
    
    });
    

    检查docs about testing async with Jasmine 1.3。这是working JSFiddle

    Jasmine 2.x会容易一些:

    it('should ....', function (done) {
    
        spyOn(MyService,'handleMessage').and.callFake(function () {
          expect(MyService.handleMessage).toHaveBeenCalled();
          done();
        });
    
        $window.postMessage('message','*');
    });
    

    另外,我不得不提一下,你必须改变添加监听器的方式

    angular.element($window).on('message', MyService.handleMessage);
    

    到那个

    angular.element($window).on('message', function (e) {
        MyService.handleMessage(e);
    });
    

    因为.on 自己注册了一个函数,所以它不会被用作附加到MyService 的方法,所以你将无法窥探它。

    【讨论】:

    猜你喜欢
    • 2019-12-24
    • 2017-11-22
    • 1970-01-01
    • 2013-10-18
    • 2015-04-14
    • 2019-05-31
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多