javascript - 如何在 Jest/Vue-test-utils 测试中导入/包含插件?

标签 javascript vue.js jestjs vue-test-utils

使用 Jest 和 Vue-test-utils 测试基本按钮实现时,测试有效,但我收到以下警告:

[Vue warn]: Unknown custom element: b-button - did you register the component correctly? For recursive components, make sure to provide the "name" option.

我有信心是因为我没有正确包含 Buefy 插件依赖项,而且我在这里没有太多经验。 这是我的基本按钮的单个文件组件:

<template>
  <b-button data-testid="base-button" @click="$emit('click')">
    {{ buttonLabel }}
  </b-button>
</template>

<script>
export default {
  props: {
    buttonLabel: {
      type: String,
      default: 'Button',
    },
  },
}
</script>

<style></style>

这是我的测试:

import { mount } from '@vue/test-utils'
import BaseButton from '@/components/base/BaseButton'

const Component = BaseButton
const ComponentName = 'BaseButton'

const global_wrapper = mount(Component, {})

describe(ComponentName, () => {
  it('should render the button', () => {
    const wrapper = global_wrapper
    const button = wrapper.find('[data-testid="base-button"]')
    expect(button.exists()).toBeTruthy()
  }),
    it('should emit the click event on a click', async () => {
      const wrapper = global_wrapper
      console.log(wrapper.html())
      const button = wrapper.find('[data-testid="base-button"]')
      button.trigger('click')

      const clickCalls = wrapper.emitted('click')

      expect(clickCalls).toHaveLength(1)
    })
})

我希望能够帮助您了解在测试中包含 Buefy b-button 组件的适当方法。

最佳答案

发布 Vue 3 解决方案。如StevenSiebert提到,createLocalVue 不再适用于 v2 @vue/test-utils(Vue 3 测试需要)。您需要在测试中使用 global 对象。

根据 docs对于 mount,要注册一次性安装插件,您可以使用:

import foo from 'foo'

mount(Component, {
  global: {
    plugins: [foo]
  }
})

要在所有测试中注册插件,您可以添加到测试设置文件,即 setup.js。请参阅docs

import foo from 'foo'

config.global.plugins = [foo]

关于javascript - 如何在 Jest/Vue-test-utils 测试中导入/包含插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70920679/

相关文章:

javascript - 如果方法是非阻塞的,则在方法中使用 this.unblock

javascript - 使用 javascript 检测对 -webkit-filter 的支持

javascript - VueJS : Modify SVG fill style with reactive variables

javascript - Jest : having trouble keeping a reference of a mock function with `jest.fn()`

javascript - Jest 全局拆解在测试完成之前运行?

javascript - 我们应该告诉 browsersync 重新加载特定的资源类型吗?

javascript - 列出锁定文件中依赖项的所有依赖项

vue.js - 带有单选按钮的 VueJS 简单工具

javascript - 我是否缺少 vue 路由器转换的某些内容?

javascript - Jest 模拟函数的内部变量并改变函数的行为?