我有以下测试效果很好
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();
});
为此,我编写了一个挂载组件的辅助方法:
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 中有一个方法。为了简单起见,我们称之为
add(num,num){
return num+num;
}
我希望能够编写一个类似如下的测试用例:
it('checks the add method works', () => {
expect(compd.add(1,2).toBe(3));
});
我不知道该怎么做。有人有什么建议吗? 这里的文档: https://v2.vuejs.org/v2/guide/unit-testing.html 不包括测试方法。
最佳答案
源代码来自 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-for 在它上面放一个 ref
`
vm.$refs.mycomponent.myMethod()
关于vue.js - 使用 Jasmine 在 Vue 组件中测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593989/