Jasmine spy() for postMessage event failing

jasmine, javascript

Solution

`postMessage` runs asynchronously, so you're hitting your expectation before the message has been posted and before the event can be fired off.

I rewrote your test like this and it works fine:

describe('Message', function () {
    
    var spy;
    
    beforeEach(function() {
        
        spy = jasmine.createSpy('message');
        
        window.addEventListener('message', function (e) {
            console.log(Object.keys(e), e.data);
            spy();
        });
        
        window.postMessage('test', '*');
        
    });

    it('Should trigger message event', function () {
        expect(spy).toHaveBeenCalled();
    });
    
});

It gets the job done here, but I don't know if it's the best solution because Jasmine provides us with the ability to test asynchronous methods: pre-2.0, you can use the `runs`, `waits`, and `waitsFor` methods (source) and 2.0+ you can use the `done` method (source).

From MDN (postMessage):

The window.postMessage method, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes.

Problem

I made a simple Jasmine test to call a spy from a postMessage but it fails. What am I missing here? ``` it('Should trigger message event', function () { var spy = jasmine.createSpy('message'); window.addEventListener('message', function (e) { console.log(Object.keys(e), e.data); // this logs as expected spy(); }); window.postMessage('test', '*'); expect(spy).toHaveBeenCalled(); }); ``` http://jsfiddle.net/4L9Vc/

Original source