【问题标题】:Better way to create related objects when testing Ember computed property?测试 Ember 计算属性时创建相关对象的更好方法?
【发布时间】:2017-04-06 18:52:39
【问题描述】:

与数百万其他应用程序一样,我们有一个模型可以选择属于另一个模型。

此模型有一个计算属性,该属性取决于该父级的存在,例如...

// some-model

parent: belongsTo('some-model'),

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

(我们使用 CP 而不是computed.alias,因为关联可以出现/消失,而alias 不会观察到变化)

一切都很好,它对我们有用。我去加个单元测试...

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

使用parent.content 设置似乎真的很老套,我想知道是否有更好、更标准的方法将模型分配给另一个模型。 Ember 文档...稀疏。

【问题讨论】:

  • 如果你使用 moduleForModel,你有access to the store
  • 您的 ember-data 版本是多少?在此查看测试 twiddle 仅使用 parent 而不是 parent.content
  • @steveax 啊,在文档中错过了。我实际上并没有意识到模型可以像那样访问商店,谢谢 - 如果你想发布答案,我会接受它,因为这看起来像是官方的做法
  • @alptugd 哦,很酷,很高兴看到它在那里工作。我们使用的是 Ember 2.10,我尝试设置为 parent,但并不满意。

标签: javascript ember.js


【解决方案1】:

关于为问题发布的 cmets,最好在测试模型时使用store。因此,以下twiddle 可能是实现给定测试场景的更好方法。如果将来其他人需要它,我将其作为答案。

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2015-09-20
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多