Search code examples
vue.jsjestjselement-uivue-test-utils

How to find elementUi's componets during unit testing using vue-test-utils's with shallowMount?


After reading vue-test-utils's document, I am trying to hand on.

Hope someone can clear my confusion.

import { mount, shallowMount } from '@vue/test-utils'
import Vue from 'vue'
import Form from '@/components/Form/index.vue'
import ElementUI from 'element-ui'

Vue.use(ElementUI)
describe('Form.vue', () => {

  //find it, pass
  it('mount', () => {
    const wrapper = mount(Form)
    const elButton = wrapper.find('.el-button')
    expect(elButton.isVueInstance()).toBe(true)
  })

  //can't find it, fail
  it('shallowMount', () => {
    const wrapper = shallowMount(Form)
    const elButton = wrapper.find('.el-button')
    expect(elButton.isVueInstance()).toBe(true)
  })
})

I can find the components given by elementui when I use 'mount'.

But maybe sometimes I'll need to use 'shallowMount'.

How can I find the components in this situation?

Thanks in advance.




Thanks for the answer, I found two approaches to fix it:

it('shallowMount', () => {
      const wrapper = shallowMount(Form)
      const elButton = wrapper.find(ElementUI.Button)
      expect(elButton.isVueInstance()).toBe(true)
    })
it('shallowMount', () => {
      const wrapper = shallowMount(Form)
      const elButton = wrapper.find({ name: 'ElButton' })
      expect(elButton.isVueInstance()).toBe(true)
    })

Solution

  • When you use shallowMount, the child components will be stubbed instead of rendered. That's why you can't find it in the second test in the way you are doing.

    One option is to do like mentioned here: https://lmiller1990.github.io/vue-testing-handbook/stubbing-components.html#automatically-stubbing-with-shallowmount

      it('shallowMount', () => {
        const wrapper = shallowMount(Form)
        expect(wrapper.find(ElButtonComponent).exists()).toBe(true)
      })