Tho*_*rin 5 javascript unit-testing ember.js ember-data ember-cli
Ember.Mixin我的应用程序中包含DS.attr()和/或包含的内容很少DS.belongsTo().我想知道我应该如何对它们进行单元测试?
默认情况下,ember-cli会生成此测试
test('it works', function(assert) {
  var MyModelObject = Ember.Object.extend(MyModelMixin);
  var subject = MyModelObject.create();
  assert.ok(subject);
});
但当我尝试与DS.attr()我交互时,我收到以下错误:
TypeError: Cannot read property '_attributes' of undefined
  at hasValue (http://localhost:4200/assets/vendor.js:90650:25)
  at Class.get (http://localhost:4200/assets/vendor.js:90730:13)
  at Descriptor.ComputedPropertyPrototype.get (http://localhost:4200/assets/vendor.js:29706:28)
  at Object.get (http://localhost:4200/assets/vendor.js:35358:19)
  at Class.get (http://localhost:4200/assets/vendor.js:49734:38)
  at Object.<anonymous> (http://localhost:4200/assets/tests.js:20126:25)
  at runTest (http://localhost:4200/assets/test-support.js:2779:28)
  at Object.run (http://localhost:4200/assets/test-support.js:2764:4)
  at http://localhost:4200/assets/test-support.js:2906:11
  at process (http://localhost:4200/assets/test-support.js:2565:24)
这让人感觉到了.最好的方法是什么?我应该DS.Model在测试中创建一个然后应用mixin吗?
谢谢 !
单元测试这样的模型mixin有点棘手,因为它需要访问商店才能创建模型.通常,商店在mixin测试中不可用,因为甚至没有容器.另外,由于我们只想测试mixin,我们不想要一个真实的模型,所以我们可以为测试创建和注册一个虚假的主机模型.这就是我这样做的方式.
首先,引入'余烬数据'并使用'ember-qunit'中的助手而不是'qunit'中的助手.替换这个:
import { module, test } from 'qunit';
有了这个:
import { moduleFor, test } from 'ember-qunit';
import DS from 'ember-data';
然后,您更新模块声明,如下所示:
moduleFor('mixin:my-model-mixin', 'Unit | Mixin | my model mixin', {
  // Everything in this object is available via `this` for every test.
  subject() {
    // The scope here is the module, so we have access to the registration stuff.
    // Define and register our phony host model.
    let MyModelMixinObject = DS.Model.extend(MyModelMixin);
    this.register('model:my-model-mixin-object', MyModelMixinObject);
    // Once our model is registered, we create it via the store in the
    // usual way and return it. Since createRecord is async, we need
    // an Ember.run.
    return Ember.run(() => {
      let store = Ember.getOwner(this).lookup('service:store');
      return store.createRecord('my-model-mixin-object', {});
    });
  }
});
完成此设置后,您可以this.subject()在单独的测试中使用一个对象进行测试.
test('it exists', function(assert) {
  var subject = this.subject();
  assert.ok(subject);
});
在这一点上,它只是一个标准的单元测试.您可能需要在Ember.run块中包装异步或计算代码:
test('it doubles the value', function(assert) {
  assert.expect(1);
  var subject = this.subject();
  Ember.run(() => {
    subject.set('someValue', 20);
    assert.equal(subject.get('twiceSomeValue'), 40);
  });
});
| 归档时间: | 
 | 
| 查看次数: | 1045 次 | 
| 最近记录: |