I'm trying to create a unit test for my app based in Vue and vue-cli with webpack template.
I read Vue documentation, vue-loader, vue-cli and vue-template/webpack (an more!). When I try to make a unit test for my component, I use this.
const Constructor = Vue.extend(MyComponent)
vm = new Constructor().$mount()
like Vue-template/webpack example and like Vue official
This work fine. but the pronlem is when my component has some props. I try to pass with this
const Constructor = Vue.extend(MyComponent)
vm = new Constructor({
myprop: 10
}).$mount()
And in my unit test, when I try to get this prop, I get undefined. How can I pass prop to my component in unit test?
const Constructor = Vue.extend(MyComponent)
vm = new Constructor({
propsData: { myprop: 10 }
}).$mount()
See: https://vuejs.org/v2/api/#propsData
What I usually do, and what I suggest is to create helper function where you can pass propsData
to the constructor - It should looks like this:
function getComponent(Component, propsData) {
let Ctor = Vue.extend(Component)
const el = document.createElement('DIV')
return new Ctor({propsData, el})
}
Usage is pretty easy:
describe('MyComponent.vue', () => {
it('should do something', () => {
const vm = getComponent(MyComponent, {
propName: 'propValue'
})
// expectation
})
})
If you don't have any props you can simply omit the passing second object to helper function
describe('MyComponent.vue', () => {
it('should do something', () => {
const vm = getComponent(MyComponent)
// expectation
})
})
you can define your props to option of data and access vueInstance.propName to get value of prop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With