javascript - How to test that a function has been called after an event was fired? -
there custom event fired in fooview
..
// views/foo_view.js this.trigger("something:happened");
the associated foocontroller
binds handler take care of event ...
// controller/foo_controller.js initialize: function() { this.fooview = new fooview(); this.fooview.bind("something:happened", this.onsomethinghappened, this); } onsomethinghappened: function(event) { // else. }
to test event handling write following test jasmine:
it("should else when happens", function() { var foocontroller = new foocontroller(); spyon(foocontroller, "onsomethinghappened"); foocontroller.fooview.trigger("something:happened"); expect(foocontroller.onsomethinghappened).tohavebeencalled(); });
though, test fails ..
fooview should else when happens. expected spy onsomethinghappened have been called. error: expected spy onsomethinghappened have been called. @ new jasmine.expectationresult (http://localhost:8888/__jasmine_root__/jasmine.js:114:32) @ null.tohavebeencalled (http://localhost:8888/__jasmine_root__/jasmine.js:1235:29) @ null.<anonymous> (http://localhost:8888/assets/foo_spec.js?body=true:225:47) @ jasmine.block.execute (http://localhost:8888/__jasmine_root__/jasmine.js:1064:17) @ jasmine.queue.next_ (http://localhost:8888/__jasmine_root__/jasmine.js:2096:31) @ jasmine.queue.start (http://localhost:8888/__jasmine_root__/jasmine.js:2049:8) @ jasmine.spec.execute (http://localhost:8888/__jasmine_root__/jasmine.js:2376:14) @ jasmine.queue.next_ (http://localhost:8888/__jasmine_root__/jasmine.js:2096:31) @ oncomplete (http://localhost:8888/__jasmine_root__/jasmine.js:2092:18) @ jasmine.spec.finish (http://localhost:8888/__jasmine_root__/jasmine.js:2350:5)
does test fail because event takes longer expectation excute?
the problem spy on function after function bound event. when jasmine create spy replace function spy on function.
so happens here, original function bound event
this.fooview.bind("something:happened", this.onsomethinghappened, this);
after that, original function replaced spy, not have effect on function pass bind
function.
the solution spy foocontroller.prototype.onsomethinghappened
before create new instance:
it("should else when happens", function() { var onsomethinghappenedspy = spyon(foocontroller.prototype, "onsomethinghappened"); var foocontroller = new foocontroller(); foocontroller.fooview.trigger("something:happened"); expect(onsomethinghappenedspy).tohavebeencalled(); });
Comments
Post a Comment