Skip to content Skip to sidebar Skip to footer

How To Test An Ember Model's Computed Property That Has Relations Dependencies?

I'm writing Qunit tests to test An Ember model, but having a hard time testing computed properties that have a relation dependency (the computed property triggers another model's c

Solution 1:

Okay, what I have so far is too much for a comment, so I'm going to do a WIP Answer.

  • I removed most of the run loops, they are only necessary for async processes.

  • I changed some of your computed properties to computed.alias properties

i.e.

phone: (->
  @get('phones.firstObject.number')
).property('phones.firstObject.number')

to

phone: Ember.computed.alias('phones.firstObject.number')
  • I ripped out most of the setup, Ember Data eagerly loads the store on its own and will use fixture ids etc without specifying it. (this part can be put back it, it just isn't necessary in this context).

i.e.

  },(container, context) ->
  container.register 'store:main', DS.Store
  container.register 'adapter:application', DS.FixtureAdapter
  context.__setup_properties__.store = -> container.lookup('store:main')
  • And I apologize in advance, I'm not a fan of coffeescript, so I put it all in js. Now the question is, if you're still seeing any issues we may need to find out what versions of Ember, ED, and Ember Qunit you are using.

http://emberjs.jsbin.com/OxIDiVU/625/edit

Solution 2:

I found this question looking for 'how to unit test a computed property that uses a hasMany'.

Here is a simple example of how I did it (thanks to Kitler):

Fridge Model:

foods: DS.hasMany('food', {async: true}),

inDateFoods: Ember.computed('foods.@each.{ignoreEndDate,endDate}', function() {
  let foods = this.get('foods');
  let now = moment();
  return foods.filter(f => f.get(ignoreEndDate) || moment(c.get('endDate')).isAfter(now));
})

So say we now want to test inDateFoods in a unit test? Then do this in your fridge model test file:

importEmberfrom'ember';
import { moduleForModel, test } from'ember-qunit';
importFridgefrom'../../../models/fridge';

Fridge.reopen({
  foods: Ember.computed(() => [])
});

moduleForModel('fridge', 'Unit | Model | fridge', {
  // Specify the other units that are required for this test.needs: ['model:food']
});

test('filters correctly', function(assert) {
  assert.expect(1);
  let model = this.subject();
  model.pushObject(Ember.Object.create({foods: [{id: 1, ignoreEndDate: false, endDate: '2050-03-08T00:00:00'});

  assert.equal(model.get('inDateFoods.length'), 1);
});

They key here is to reopen your model to remove the has many, and push the object after doing this.subject. Before doing the reopen we were getting the error All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]] error.

Post a Comment for "How To Test An Ember Model's Computed Property That Has Relations Dependencies?"