我正在尝试编写单元测试来测试我的 Controller 。我有一个在模型上使用计算属性的计算属性。
我不确定如何设置测试以将数据加载到模型中。
这是我的模型:
App.User = DS.Model.extend({
name: DS.attr('string'),
roles: DS.hasMany('role'),
isInstructor: function(){
return this.hasRole('instructor');
}.property('roles'),
hasRole: function(role_name){
var roles = this.get('roles');
if(!Ember.isEmpty(roles)){
return roles.any(function(role){
return role.get('name') === role_name;
});
}
return false;
}
});
这里是我的 Controller :
App.MyClassDetailsController = Ember.ObjectController.extend({
students: function () {
return this.get('users').filter(function (user) {
return !user.get('isInstructor');
});
}.property('content.users.@each')
});
在我的测试中,当我为 Controller 设置内容时,我这样做:
myClassDetailsController.set('model', Ember.ObjectProxy.create({
id: 389,
name: 'bfcoding 101',
users: Ember.ArrayProxy.create({
content: [
Ember.ObjectProxy.create({id: 1, name: 'Joe', roles: Ember.ArrayProxy.create({content: [Ember.ObjectProxy.create({name: 'instructor'})]})}),
Ember.ObjectProxy.create({id: 2, name: 'vs', roles: Ember.ArrayProxy.create({content: [Ember.ObjectProxy.create({name: 'student'})]})}),
Ember.ObjectProxy.create({id: 3, name: 'Volcano', roles: Ember.ArrayProxy.create({content: [Ember.ObjectProxy.create({name: 'student'})]})})
]
})
}));
这显然不能正确加载它。因为当我调用那个学生方法时:
myClassDetailsController.get('students.length')
它返回所有用户。
这是一个jsbin http://jsbin.com/zafod/1/
在 jsbin 中,当它过滤所有用户时,永远不会调用 isInstructor 计算属性,因为从未加载模型数据(我推测)。当我进行该调用时,它返回未定义。
那么我该如何将这些数据加载到模型中呢?
谢谢!
最佳答案
isInstructor
存在于 App.User
的实例上,而不是存在于 Ember.ObjectProxy
实例上。您要么需要创建 App.User
的实例,要么只在代理实例上定义 isInstructor
。
我个人会选择后者。在一个完美的单元测试世界中,您测试的是 Controller ,而不是 App.User
,因此其他一切都应该被模拟或假定工作完美。显然,当您切换到集成测试时,这一切都会改变,但同样,这是单元测试。
Ember.ObjectProxy.create({id: 1, isInstructor: true, name: 'Joe', roles: Ember.ArrayProxy.create({content: [Ember.ObjectProxy.create({name: 'instructor'})]})}),
关于javascript - 如何在 Controller 的 Ember.js 单元测试中设置模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813276/