【问题标题】:How to find elementUi's componets during unit testing using vue-test-utils's with shallowMount?如何在单元测试期间使用带有 shallowMount 的 vue-test-utils 找到元素组件?
【发布时间】:2019-09-04 16:07:58
【问题描述】:

看完vue-test-utils的文档,我正在努力动手。

希望有人能解开我的困惑。

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

我使用'mount'时可以找到elementui给出的组件。

但有时我可能需要使用“shallowMount”。

在这种情况下如何找到组件?

提前致谢。




感谢您的回答, 我找到了两种解决方法:

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

【问题讨论】:

    标签: vue.js jestjs element-ui vue-test-utils


    【解决方案1】:

    当您使用 shallowMount 时,子组件将被存根而不是渲染。这就是为什么您无法以您的方式在第二次测试中找到它。

    一种选择是像这里提到的那样做: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)
      })
    
    

    【讨论】:

    • 能找到el键吗?我的意思是可能类似于wrapper.find('el-button')?因为我只想触发点击 el 按钮。而且我认为使用mount 渲染所有内容是没有必要的。
    • @Billyyyyy3320 如果您的问题仍未得到解答,您可以使用 wrapper.find({ name: 'ElButton' }).vm.$emit(‘click') 而不是 wrapper.find('el-button').trigger('click'); 因为 el-button 本身就是一个组件,并且由于它的 shallowMount(ing)父组件(本例中为 Form)。
    猜你喜欢
    • 2018-04-29
    • 2019-09-08
    • 2019-08-07
    • 2021-09-11
    • 2019-01-27
    • 2019-10-27
    • 1970-01-01
    • 2019-07-16
    • 2019-02-22
    相关资源
    最近更新 更多