2017-04-24 171 views
1

我有以下的測試偉大的工程測試方法使用茉莉花

it('does not render chapter div or error div',() => { 
     const payLoad = chapter; 
     const switcher = 'guild'; 
     var vm = getComponent(payLoad, switcher).$mount(); 
     expect(vm.$el.querySelector('#chapter-card')).toBeNull(); 
     expect(vm.$el.querySelector('#error-card')).toBeNull(); 

    }); 

要做到這一點,我寫的是安裝一個部件的helper方法:

const getComponent = (prop1) => { 
     let vm = new Vue({ 
      template: '<div><compd :payLoad="group" :index="index" "></compd ></div></div>', 
      components: { 
       compd, 
      }, 
      data: { 
       payLoad: prop1, 

      }, 

     }) 
     return vm; 
    } 
然而

,我有一個方法在我的vue組件compd中。對於simplicitys的緣故,讓我們把它叫做

add(num,num){ 
return num+num; 
} 

我希望能夠寫出類似下面的一個測試用例:

it('checks the add method works',() => { 

     expect(compd.add(1,2).toBe(3)); 

    }); 

我無法弄清楚如何做到這一點。有沒有人有任何建議? 此處的文檔: https://vuejs.org/v2/guide/unit-testing.html 不包括測試方法。

+1

你錯過了(compd.add(1,2)' – thanksd

+0

謝謝,但這不是問題 – Programatt

+0

它應該'expect(compd.add(1,2))。toBe(3)' – thanksd

回答

0

源代碼vue repo

正如你所看到的方法被簡單地稱爲實例上的

const vm = new Vue({ 
    data: { 
    a: 1 
    }, 
    methods: { 
    plus() { 
     this.a++ 
    } 
    } 
}) 
vm.plus() 
expect(vm.a).toBe(2) 

您還可以通過$options訪問方法就像在這種情況下(vue source code

const A = Vue.extend({ 
    methods: { 
    a() {} 
    } 
}) 
const vm = new A({ 
    methods: { 
    b() {} 
    } 
}) 
expect(typeof vm.$options.methods.a).toBe('function') 

更新: 要測試子組件,請使用$children來訪問必要的孩子。例如

var childToTest = vm.$children.find((comp)=>comp.$options.name === 'accordion')` assuming name is set to `accordion` 

之後,你可以

childToTest.plus(); 
vm.$nextTick(()=>{ 
    expect(childToTest.someData).toBe(someValue) 
    done(); //call test done callback here 
}) 

如果你有一個子組件,而不是V型的就可以把ref `

vm.$refs.mycomponent.myMethod()