I'm trying to use Jasmine 2.0 to write unit tests for some logic in an AngularJS app, but the logic is inside an event listener. From the controller:
window.addEventListener('message', function(e) {
if (e.data === "sendMessage()") {
$scope.submit();
}
}, false);
And from the test file:
describe("post message", function() {
beforeEach(function(done) {
var controller = createController(controllerParams);
spyOn($scope, 'submit');
window.postMessage('sendMessage()', '*');
done();
});
it('should submit on a sent message', function (done) {
expect($scope.submit).toHaveBeenCalled();
done();
});
});
But the test fails, the spy never being hit. Extra info from putting in console debug statements:
window.addEventListener
in the controller IS getting called.- The
beforeEach
andit
block are both getting called. - The above message handler in the controller is not getting called during the test.
- The message sent in this test is eventually being receievd by the message handler, several times, but not until after the test ends.
What is my test missing here?