Вычисляемое свойство модульного теста на контроллере Ember

Код из моего controllers/cart.js:

export default Ember.Controller.extend({
  cartTotal: Ember.computed('[email protected]', 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, чтобы тест прошел?

Спасибо!


person zshnr    schedule 08.07.2015    source источник
comment
Можете ли вы добавить остальную часть кода вашего теста?   -  person Patsy Issa    schedule 08.07.2015
comment
сделано. отредактировал пост   -  person zshnr    schedule 08.07.2015


Ответы (2)


Может что-то в этом духе?

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');
});
person Kori John Roys    schedule 08.07.2015
comment
да! С небольшой разницей: вместо Product.create мы даже не могли импортировать нашу модель и вместо этого использовали Ember.Object.create На самом деле с Product.create у меня были ошибки. Он работал с Ember.Object.create. Если вы внесете изменения в свой ответ, я отмечу его как правильный. Большое спасибо за твою помощь! - person zshnr; 08.07.2015
comment
Да, я просто взял примеры из разных источников, и у меня нет настоящего приложения ember-cli для тестирования, поэтому я не знаю, почему импорт модели не работает. Ну что ж. - person Kori John Roys; 08.07.2015
comment
это был импорт. с ошибкой не удалось использовать store.createRecord вместо Product.create. - person zshnr; 08.07.2015

Один из способов справиться с этим — заглушить модель в хуке 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);
  }
});
person Patsy Issa    schedule 08.07.2015
comment
Спасибо. Я отредактировал свой первый пост с результатом, который я получил, попробовав это. У меня есть ощущение, что я, возможно, делаю это неправильно, но я чувствую, что стал ближе. - person zshnr; 08.07.2015
comment
Ваш ответ шел по правильному пути, хотя :) - person zshnr; 08.07.2015
comment
Ой, использовал объект вместо массива x.x - person Patsy Issa; 09.07.2015