我的controllers/cart.js:的代码
export default Ember.Controller.extend({
cartTotal: Ember.computed('model.@each.subTotal', function() {
return this.model.reduce(function(subTotal, product) {
var total = subTotal + product.get('subTotal');
return total;
}, 0);
})
)};此计算的属性循环遍历模型中的所有元素,添加subTotal属性的所有值,返回一个cart total。
cart-test.js
import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:cart', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
var controller = this.subject();
assert.ok(controller);
});
test('cartTotal function exists', function(assert) {
var controller = this.subject();
assert.equal(controller.get('cartTotal'), 30, 'The cart total function exists');
});测试在TypeError: Cannot read property 'reduce' of null中失败,因为它显然没有要循环的模型。
如何模拟cartTotal计算属性的依赖项以通过测试?
谢谢!
发布于 2015-07-08 15:30:45
有可能是这样的吗?
import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
var products = [
Ember.Object.create({ name: 'shoe', subTotal: 10 }),
Ember.Object.create({ name: 'shirt', subTotal: 20 })];
var model = Ember.ArrayProxy.create({
content: Ember.A(products)
});
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject();
}
});
test('cartTotal', function(assert) {
this.controller.set('model', model);
assert.equal(this.controller.get('cartTotal'), 30, 'The cart total function exists');
});发布于 2015-07-08 14:24:08
处理这一问题的一种方法是在beforeEach钩子中对模型进行存根:
var sampleModel = [ // sample data that follows your actual model structure ]
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject(); // allows you to access it in the tests without having to redefine it each time
this.controller.set('model', sampleModel);
}
});https://stackoverflow.com/questions/31294392
复制相似问题