gpt4 book ai didi

javascript - 如何测试事件触发后是否调用了函数?

转载 作者:可可西里 更新时间:2023-11-01 02:19:58 25 4
gpt4 key购买 nike

FooView 中触发了自定义事件..

// views/foo_view.js

this.trigger("something:happened");

关联的 FooController 绑定(bind)一个处理程序来处理事件 ...

// 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)

测试失败是否是因为事件执行的时间比预期的要长?

最佳答案

问题是您在函数绑定(bind)到事件后监视该函数。当 jasmine 创建一个 spy 时,它会用另一个函数替换你监视的函数。

那么这里发生的是原始函数绑定(bind)到事件

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();
});

关于javascript - 如何测试事件触发后是否调用了函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18321993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com