[英]How do we unit test a Model Mixin with 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進行單元測試有點棘手,因為它需要訪問商店才能創建模型。 通常,在混合測試中無法使用該存儲,因為甚至沒有容器。 另外,由於我們只想測試混入,所以我們不需要真正的模型,因此我們可以為測試創建和注冊虛擬主機模型。 這是我的方法。
首先,輸入“ ember-data”並使用“ 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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.