Testing window.postMessage directive

混江龙づ霸主 提交于 2019-12-11 10:39:28

问题


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

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/ (including jasmine test)

I'd appreciate your help! Michael


回答1:


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

});

Check the docs about testing async with Jasmine 1.3. And here is a working JSFiddle.

It would be a bit easier in 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);

to that

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

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.



来源:https://stackoverflow.com/questions/30939566/testing-window-postmessage-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!