Testing postMessage with Jasmine async doesn't work

感情迁移 提交于 2019-12-04 03:17:56

It is happening because in your beforeEach block you call window.postMessage() (which is asynchronous and you don't know when it's gonna execute) and then you call done() right after it as it would be synchronous code. But window.postMessage() as async, and basically you need to call done() when your async operation is complete. It could be done like this:

beforeEach(function(done) {  
    spyOn(someObject, 'submit').and.callFake(function () {
      done();
    });
});

So when your spy executes, then async operation is considered complete.

This could be expressed even shorter:

beforeEach(function(done) {  
    spyOn(someObject, 'submit').and.callFake(done);
});

Here is the full code:

var someObject = {
  submit: function () {
    console.log('Submit');
  }
};

window.addEventListener('message', function(e) {
  if (e.data === "sendMessage()") {
    someObject.submit();
  }
}, false);

// Test

describe('window.postMessage', function () {

  beforeEach(function(done) {  
    spyOn(someObject, 'submit').and.callFake(function () {
      done();
    });
    window.postMessage('sendMessage()', '*');
  });

  it('should submit on a sent message', function () {
    expect(someObject.submit).toHaveBeenCalled();
  });

});

See a working JS Bin: http://jsbin.com/xikewogagu/1/edit?html,js,console,output

I did not use Angular in this sample because it is reproducible with a pure JS.

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