Ember.js Property Initialization Explanation

I am just starting out with Ember and am facing this problem when writing jasmine tests.

Given that I have the following code

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) 

And I am writing the next test.

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

I expected both tests to pass, but instead the second test will fail with a message

The expected 17.4 is 10.2.

It seems that the state of the first test is being poured into the second test. Can someone more knowledgeable than me explain how Ember controls the controller and why this happens?

Thanks!

+4
source share
1 answer

The reason for the test failure is the default initialization of @line 4.

You must either set the initial value in the init method in App.RecipeController , or pass the value when creating the instance:

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

or

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

You should take a look at section 6 of this article .

+5
source

Source: https://habr.com/ru/post/1442082/


All Articles