Unit testing 余烬控制器上的单元测试计算属性

Unit testing 余烬控制器上的单元测试计算属性,unit-testing,ember.js,ember-cli,qunit,ember-qunit,Unit Testing,Ember.js,Ember Cli,Qunit,Ember Qunit,mycontrollers/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');

mycontrollers/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);
  })
)};
此计算属性在模型中的所有元素上循环,添加
小计
属性的所有值,返回
购物车总计

购物车测试.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:无法读取null的属性'reduce',因为它显然没有要循环的模型

如何模拟
cartotal
computed属性的依赖关系以使测试通过


谢谢

处理此问题的一种方法是在每个钩子之前将模型存根在
中:

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

也许是这样的

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

您可以添加测试的其余代码吗?完成。编辑了帖子谢谢。我已经编辑了我的第一篇文章,结果是我尝试了这个。我有一种感觉,我可能做得不对,但我觉得我离得更近了。不过,你的答案是正确的:)Oups,使用对象而不是数组x.xyes!有一点不同:我们甚至无法导入我们的模型,而是使用
Ember.Object.create
而不是
产品。create
我遇到了错误。它与Ember.Object.create一起工作。如果你对你的答案作了修改,我会把它标为正确答案。非常感谢你的帮助!是的,我只是从不同的来源提取了一些示例,没有一个实际的ember cli应用程序来测试这些东西,所以我不知道为什么导入模型不起作用。哦,好吧,那是进口货。使用
store.createRecord
而不是
Product.create
失败,出现错误。