Unit Testing Model Computed Properties (Depending On Other DS.Model Objects)


#1

Hi All,

I’ve been using Ember for a couple of months now, and I’ve just decided to use it to start a new project. I’m determined to make this my first fully test-driven project, and while things are going well, I hit a snag yesterday that I thought I would bring to the community hoping for advice on my approach.

I’ve got a “decision-event” model with a “modifiers” enum property representing a hasMany relationship with the “modifier” model. This decision-event model also has a choiceSelected property which will be a number representing the index of the modifier chosen by the user.

Currently, I’m trying to build a selectedModifier computed property directly referencing the chosen modifier by computing something along the lines of…

this.get('modifiers').objectAt(this.get('choiceSelected'));

I imagine the computed property will look like this…

      selectedModifier: Ember.computed('choiceSelected', function() {
        return this.get('modifiers').objectAt(this.get('choiceSelected'));
      })

But I can’t wrap my head around how to write a failing unit test to drive this. I feel like it should instantiate two ‘modifier’ objects in the ‘modifiers’ enum property, then set the choiceSelected, and compare that the selectedModifier is the proper modifier in the “modifiers” enum. but I’m not sure how to load proper DS.Model objects into the subject for testing. I’m currently working with this:

test('selectedModifier computed property updates to proper modifier when choiceSelected is set', function(assert) {
  const model = this.subject({ modifiers: [{dummyProp: "modifier_1"}, {dummyProp: "modifier_2"}] });
  Ember.run(()=>{
    model.set('choiceSelected', 0);
    assert.equal(model.get('selectedModifier'), this.get("modifiers").objectAt(0));
  });
});

This fails as per:

Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object],[object Object]]

Which makes complete sense. To get closer to a passing test, though, how can I turn those obj literals into DS.Model objects?

Or am I taking the wrong approach with my testing? Am I missing something obvious?

Thanks for any advice! Looking forward to continuing on with the Ember development.

Jon


#2

Having recently hit the same thing, this is the best I have been able to suss out:

const model = this.subject();

Ember.run(() => {
    const m1 = this.store().createRecord('othermodel', { attrs });
    const m2 = this.store().createRecord('othermodel', { attrs });
    model.set('relationship', [ m1, m2 ]);
});

model.get('propertyRelyingOnRelationship');

The gotcha was the first time I tried it using this.store.createRecord, which, of course, fails :slight_smile: