我正在使用 Jasmine 对 EmberJS 项目进行单元测试,但我在使用 Ember 的需求 API 时遇到了问题。
当我尝试运行 jasmine 测试时,如果有问题的 Controller 具有“需要”以及调用的 init 函数,它们将无法创建 Controller 实例
this._super()
我得到这个控制台错误
"Cannot call method 'has' of null"
当我尝试调试时,它让我一路进入 Ember 的内部,但我一无所获。
谁知道我做错了什么
Application.SearchPendingController = Ember.ObjectController.extend({
needs: ['searchResults', 'search'],
shouldDisable: false,
searchResultsController: null,
init: function () {
this._super();
this.set('searchResultsController', this.controllerFor('searchResults'));
this.get('controllers.search.content').reload();
this.get('controllers.searchResults').set('content', this.get('controllers.search.content.results'));
},
transitionToResults: function () {
console.log('yay');
}.observes('this.searchResultsController.content')
});
当我尝试创建这个 Controller 时,jasmine 测试抛出一个错误
var searchPendingController = Application.SearchPendingController.create();
有人对此有任何想法吗?
最佳答案
当您创建 Controller 时,Ember.js 在 init 方法中检查依赖项(需要
)。检查依赖项假设您有一个 Ember.js 应用程序,并且该应用程序的容器位于 Controller 的 container
属性中。如果 Ember.js 为您创建了 Controller ,这一切都很好。
您的错误正在发生here ,在 verifyDependencies
函数中。
如果您不希望 Ember.js 为您创建 Controller 并希望手动创建它(这就是您在这里所做的),您将需要手动设置 Controller 的 container
应用程序容器的属性。
Application.SearchPendingController.reopen({
container: Application.__container__
});
单元测试 Controller 很棘手,需要您深入了解 Ember.js 的内部结构。我的建议是,让 Ember.js 为您创建 Controller ,并使用集成测试而不是对它们进行单元测试。
关于javascript - Jasmine 测试失败 EmberJS 需要 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15548109/