2017-04-03 7 views
7

私はVue CLIのVueJSを使用しています。だから私のすべてのコンポーネントは.vueフォーマットです。VueJSで計算されたプロパティをテストするにはどうすればよいですか?

私のコンポーネントの1つでは、データセクションにfieldsという配列があります。

//Component.vue 
data() { 
    return { 
    fields : [{"name" : "foo", "title" : "Foosteria"}, {"name" : "bar", "title" : "Barrista"}] 
    } 
} 

私は、私はこのようjasmineで私のユニットテストのすべてを設定していると、彼らが正常に動作fields

//Component.vue 
computed : { 
    subsetOfFields() { 
     // Something else in component data determines this list 
    } 
} 

のサブセットである計算プロパティを持っています。他のすべてのために

//Component.spec.js 
import Vue from 'vue' 
import MyComponent from 'Component.vue' 
describe("Component test", function() { 
     var myComponentVar = new Vue(MyComponent); 
     var vm = myComponentVar.$mount(); 

     beforeEach(function() { 
     vm = myComponentVar.$mount(); 
    ); 

     afterEach(function() { 
     vm = myComponentVar.$destroy(); 
     }); 

     it("First spec tests something", function() { 
      ... 
     }); 

}); 

spec内部に何かをして、その後、dataオブジェクトにアサーションを実行すると、うまく動作します。しかし、subsetOfFieldsでアサーションを実行すると、常に空の配列が返されます。なぜそうなのか?それをテストできるように私は何をすべきですか?

参考までに、別のdescribeブロックの中に仕様を入れ子にして、さらにfieldsアレイを初期化するbeforeEachを追加しようとしました。うまく行かなかった。

ただし、beforeEachファンクションの内部でfieldsを初期化しています。しかし、他のスペックのモックデータでfields配列を初期化したくありません。

+0

これは実際のVueプロジェクトのcomponent.spec.jsです。あなたはそこに必要なものを見つけることができます。 https://github.com/vuejs/vue/blob/dev/test/unit/features/options/computed.spec.js – Bert

+0

@BertEvans、私はすでにその例でテクニックを試していました。彼はすでにその中のデータでコンポーネントを初期化しています。 しかし、18行目では、 'a'のデータは1から2に変化し、19行目では' b'で変更が期待されます。同じことをしましたが、うまくいかず、理由が分かりません。 –

答えて

3

私はテストの話、あなたが見てする必要がありますセクションでは、Vue.nextTick(...)節

https://alligator.io/vuejs/unit-testing-karma-mocha/

私が話しているブロックでは、このリンクに出くわしました

import Vue from 'vue'; 
// The path is relative to the project root. 
import TestMe2 from 'src/components/TestMe2'; 

describe('TestMe2.vue',() => { 
    ... 
    it(`should update when dataText is changed.`, done => { 
    const Constructor = Vue.extend(TestMe2); 

    const comp = new Constructor().$mount(); 

    comp.dataProp = 'New Text'; 

    Vue.nextTick(() => { 
     expect(comp.$el.textContent) 
     .to.equal('New Text'); 
     // Since we're doing this asynchronously, we need to call done() to tell Mocha that we've finished the test. 
     done(); 
    }); 
    }); 
}); 
+1

質の高い回答を提供するために、この[回答方法​​](http://stackoverflow.com/help/how-to-answer)をお読みください。 – thewaywewere

関連する問題