Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass props to component in Unit Test

Tags:

vue.js

vuejs2

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?

like image 509
jmanuelrosa Avatar asked Apr 24 '17 08:04

jmanuelrosa


3 Answers

const Constructor = Vue.extend(MyComponent)
vm = new Constructor({
    propsData: { myprop: 10 }
}).$mount()

See: https://vuejs.org/v2/api/#propsData

like image 110
Linus Borg Avatar answered Sep 23 '22 05:09

Linus Borg


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
  })
})
like image 39
Belmin Bedak Avatar answered Sep 23 '22 05:09

Belmin Bedak


you can define your props to option of data and access vueInstance.propName to get value of prop

like image 26
Kermit Avatar answered Sep 25 '22 05:09

Kermit