vendredi 7 avril 2017

Better way to create related objects when testing Ember computed property?

Like millions of other apps, we have a model that optionally belongs to another.

This model has a computed property that depends on the existence of that parent, like...

// some-model

parent: belongsTo('some-model'),

hasParent: Ember.computed('parent.id', function() {
  return Ember.isPresent(this.get('parent.id');
}),

(We use a CP instead of computed.alias because the association can appear/disappear and alias does not observe changes)

All well and good, it works for us. I went to add a unit test...

test('hasParent', function(assert) {
  const someModel = this.subject({ id: 1, name: 'Mr. Model, Sr' });

  assert.equal(someModel.get('hasParent'), false,
    'returns false when no parent ID');

  const childModel = this.subject({ name: 'Little Model, Jr.' });

  childModel.set('parent.content', someModel);

  assert.equal(childModel.get('hasParent'), true,
  'returns true when has parent with ID');

  childModel.set('parent.content', null);

  assert.equal(childModel.get('hasParent'), false,
    'returns false when no parent ID');
});

Setting with parent.content seems really hacky, and I wanted to know if there is a better, more standard way of assigning a model to another. Ember docs are... sparse.




Aucun commentaire:

Enregistrer un commentaire