angularjs - Testing window.postMessage directive -
i'm having trouble testing directive enables cross-document messaging registering message handler:
.directive('messaging', function ($window, myservice) { return { link: function () { angular.element($window).on('message', myservice.handlemessage); } }; })
all want unit test when directive compiled, , window.postmessage('message','*')
called, message handler should called:
http://jsfiddle.net/mhu23/l27wqn14/ (including jasmine test)
i'd appreciate help! michael
your using original window
api, not mocking it, method postmessage
keep it's asynchronous behavior. knowing that, tests should written in asynchronous way. in jsfiddle have jasmine 1.3, test should kinda this:
it('should ....', function () { var done = false; spyon(myservice,'handlemessage').andcallfake(function () { // set flag, let jasmine know when callback called done = true; }); runs(function () { // trigger async call $window.postmessage('message','*'); }); waitsfor(function () { // jasmine waits until done becomes true i.e. when callback called return done; }); runs(function () { expect(myservice.handlemessage).tohavebeencalled(); }); });
check docs testing async jasmine 1.3. , here working jsfiddle.
it 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, have mention, have change how add listener this
angular.element($window).on('message', myservice.handlemessage);
to that
angular.element($window).on('message', function (e) { myservice.handlemessage(e); });
because .on
registers function itself, won't used method attached myservice
, won't able spy on it.
Comments
Post a Comment