gpt4 book ai didi

javascript - 单元测试 Backbone.Marionette 监听器

转载 作者:行者123 更新时间:2023-11-28 00:59:31 25 4
gpt4 key购买 nike

我想检查哪些监听器附加到我的 Marionette 组件,例如 Controller :

组件示例代码:

var MyController =  Marionette.Controller.extend({
initialize: function () {

this.listenTo(OtherModule, "start", function () {
// something happens here
});
this.listenTo(OtherModule, "stop", function () {
// something happens here
});

})
});

var myController = new MyController();

单元测试示例代码:

describe("MyController", function () {
it("should have 2 listeners registered", function () {
// ?
});
});

我可以触发事件并查看我想要使用的函数是否使用 jasmine 的 spyOn 方法执行,但我很好奇是否有直接可用的附加事件列表组件。

如何检查我的组件正在监听什么?

最佳答案

我认为您正在以错误的方式进行单元测试 - unit tests should check that your object interacts with the outside world in the expected way. They shouldn't be concerned with implementation details (就像对象拥有的事件监听器的确切数量)。

话虽如此,您可以使用 _listeners (Backbone 1.0.x) 或 _listeningTo (Backbone 1.1.x) 属性:

var controller = new MyController;

describe("MyController", function () {
it("should have 2 listeners registered", function () {
expect(Object.keys(controller._listeners).length).toEqual(2)
});
});

Source - Marionette.Controller 扩展了 Backbone.Events,其中 stores listeners在该属性中。

我不会在单元测试中使用这种方法,但它对于调试内存泄漏非常有用。

关于javascript - 单元测试 Backbone.Marionette 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25781279/

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