在 Ember 控制器上计算 属性 单元测试

Unit test computed property on an Ember controller

来自我的 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.

购物车-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 计算的 属性 的依赖关系以使测试通过?

谢谢!

处理此问题的一种方法是在 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);
  }
});

也许是这样的?

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