测试window.postMessage指令 [英] Testing window.postMessage directive

查看:190
本文介绍了测试window.postMessage指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble testing my directive which enables cross-document messaging by registering a message handler:

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

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

All I want to unit test is that when this directive is compiled, and window.postMessage('message','*') is called, my message handler should be called:

http:// jsfiddle。 net / mhu23 / L27wqn14 / (包括茉莉花测试)

感谢您的帮助!
Michael

I'd appreciate your help! Michael

推荐答案

您使用的是原始窗口 API,你没有嘲笑它,所以方法 postMessage 将保持它的异步行为。知道这一点,测试应该以异步方式编写。在JSFiddle中你有Jasmine 1.3,所以测试看起来应该是这样的:

Your are using original window API, you are not mocking it, so the method postMessage will keep it's asynchronous behavior. Knowing that, tests should be written in an asynchronous way. In JSFiddle you have Jasmine 1.3, so test should look kinda like this:

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();
    });

});

检查关于使用Jasmine 1.3测试异步的文档。这是一个工作JSFiddle

Jasmine 2.x

it('should ....', function (done) {

    spyOn(MyService,'handleMessage').and.callFake(function () {
      expect(MyService.handleMessage).toHaveBeenCalled();
      done();
    });

    $window.postMessage('message','*');
});

另外,我必须提一下,你必须改变你从这里添加一个监听器的方式

Also, I have to mention, that you have to change how you add a listener from this

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

到那个

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

因为 .on 注册一个函数本身,它不会被用作附加到 MyService 的方法,所以你将无法监视它。

because .on registers a function itself, it won't be used as a method attached to the MyService, so you won't be able to spy on it.

这篇关于测试window.postMessage指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆