[英]How to test that a function has been called after an event was fired?
在FooView
觸發了自定義事件..
// views/foo_view.js
this.trigger("something:happened");
關聯的FooController
綁定一個處理程序來處理事件......
// controller/foo_controller.js
initialize: function() {
this.fooView = new FooView();
this.fooView.bind("something:happened", this.onSomethingHappened, this);
}
onSomethingHappened: function(event) {
// Do something else.
}
為了測試事件處理,我將為Jasmine編寫以下測試:
it("should do something else when something happens", function() {
var fooController = new FooController();
spyOn(fooController, "onSomethingHappened");
fooController.fooView.trigger("something:happened");
expect(fooController.onSomethingHappened).toHaveBeenCalled();
});
雖然,測試失敗..
FooView should do something else when something happens.
Expected spy onSomethingHappened to have been called.
Error: Expected spy onSomethingHappened to have been called.
at new jasmine.ExpectationResult (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:114:32)
at null.toHaveBeenCalled (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:1235:29)
at null.<anonymous> (http://localhost:8888/assets/foo_spec.js?body=true:225:47)
at jasmine.Block.execute (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:1064:17)
at jasmine.Queue.next_ (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2096:31)
at jasmine.Queue.start (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2049:8)
at jasmine.Spec.execute (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2376:14)
at jasmine.Queue.next_ (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2096:31)
at onComplete (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2092:18)
at jasmine.Spec.finish (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2350:5)
測試失敗是否因為事件執行時間比預期長?
問題是您在函數綁定到事件后監視函數。 當 jasmine 創建一個 spy 時,它將用另一個函數替換您監視的函數。
那么這里發生的是原始函數綁定到事件
this.fooView.bind("something:happened", this.onSomethingHappened, this);
之后,原始函數被 spy 替換,但這不會對您傳遞給bind
函數的函數產生任何影響。
解決方案是在創建新實例之前監視FooController.prototype.onSomethingHappened
:
it("should do something else when something happens", function() {
var onSomethingHappenedSpy = spyOn(FooController.prototype, "onSomethingHappened");
var fooController = new FooController();
fooController.fooView.trigger("something:happened");
expect(onSomethingHappenedSpy).toHaveBeenCalled();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.