首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ember控制器上的单元测试计算属性

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

Stack Overflow用户
提问于 2015-07-08 13:36:17
回答 2查看 2.5K关注 0票数 2

我的controllers/cart.js:的代码

代码语言:javascript
复制
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

代码语言:javascript
复制
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计算属性的依赖项以通过测试?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-08 15:30:45

有可能是这样的吗?

代码语言:javascript
复制
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');
});
票数 6
EN

Stack Overflow用户

发布于 2015-07-08 14:24:08

处理这一问题的一种方法是在beforeEach钩子中对模型进行存根:

代码语言:javascript
复制
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);
  }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31294392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档