Ember.js属性初始化说明

时间:2012-10-25 14:52:30

标签: ember.js

我刚刚开始使用Ember并在编写一些茉莉花测试时遇到了这个问题。

鉴于我有以下代码

App.RecipeController = Ember.Controller.extend
  selectedGrain: null
  amount: null
  recipeGrains: Ember.A()

  totalWeight: (->
    weight = 0
    @get('recipeGrains').forEach (grain) ->
      weight += grain.get('weight')
    weight
  ).property('recipeGrains.@each')

  addGrain: ->
    grain = Ember.Object.create
      name: @get('selectedGrain').get('name')
      weight: parseFloat(@get('amount'))
    @get('recipeGrains').pushObject(grain)
    @set('selectedGrain', null)
    @set('amount', null)

我写了以下测试。

describe("Controllers", function() {
  describe("NewRecipeController", function() {
    var controller;

    beforeEach(function() {
      controller = Brewery.NewRecipeController.create();
    });

    it("calculates the correct total weight", function() {
      var grains = controller.get('recipeGrains');
      grains.pushObject(Ember.Object.create({weight: 4.0}));
      grains.pushObject(Ember.Object.create({weight: 3.2}));
      expect(controller.get('totalWeight')).toEqual(7.2);
    });

    it ("adds grains based on its selected grain", function() {
      controller.set('selectedGrain', Ember.Object.create({name: "Wheat"}));
      controller.set('amount', '10.2');
      controller.addGrain();
      expect(controller.get('totalWeight')).toEqual(10.2);
    });
  });
});

我预计两个测试都会通过,但第二个测试会失败并显示消息

  

预计17.4等于10.2。

似乎第一次测试的状态正在溢出第二次测试。有人比我更了解如何解释Ember如何处理控制器状态以及为什么会发生这种情况?

谢谢!

1 个答案:

答案 0 :(得分:5)

您的测试失败的原因是默认值初始化@第4行。

您应该在init中的App.RecipeController方法中设置初始值,或者在创建实例时传递值:

App.RecipeController = Ember.Controller.extend
  init: ->
    @set 'recipeGrains', Ember.A()

controller = Brewery.NewRecipeController.create({ recipeGrains: Ember.A() });

您应该查看section 6 of this article