2016-09-20 1 views
5

DS.attr() 및/또는 DS.belongsTo()이 포함 된 앱에는 Ember.Mixin이 거의 없습니다. 어떻게 단위 테스트를해야하는지 궁금 해서요?모델 믹서를 ember-cli로 어떻게 단위 테스트합니까?

기본적으로, 엠버 - 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을 적용해야합니까?

감사합니다.

답변

4

모델을 만들기 위해 상점에 액세스해야하기 때문에 이처럼 모델 믹스를 단위 테스트하는 것은 약간 까다 롭습니다. 일반적으로 컨테이너가 없기 때문에 믹스 인 테스트에서는 매장을 사용할 수 없습니다. 또한 mixin을 테스트하기를 원하기 때문에 모델을 필요로하지 않으므로 테스트 용으로 가짜 호스트 모델을 만들고 등록 할 수 있습니다. 여기 내가 어떻게 했어.

먼저 'ember-data'를 가져 와서 'qunit'의 주식 도우미 대신 'ember-qunit'의 도우미를 사용하십시오. 이 교체 :

import { module, test } from 'qunit'; 

을두고 : 당신이 장소에서이 설정을 일단

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()를 사용할 수 있습니다

import { moduleFor, test } from 'ember-qunit'; 
import DS from 'ember-data'; 

그런 다음,이 같은 모듈 선언을 업데이트 개별 테스트에서 테스트 용 객체를 얻습니다.

이 시점에서이 테스트는 단지 표준 단위 테스트 일뿐입니다. 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); 
    }); 
}); 
관련 문제