0

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)
    })

1 Answer 1

1

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)
  })

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to find the el-button? I mean maybe something like wrapper.find('el-button')? Cause I just wanna trigger click on el-button. And I think that's kinda unnecessary to use mount to render everything.
@Billyyyyy3320 if your question is still unanswered, you can do wrapper.find({ name: 'ElButton' }).vm.$emit(‘click') instead of wrapper.find('el-button').trigger('click'); cuz el-button is a component on its own and is stubbed out due to shallowMount(ing) of its parent component (Form in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.