我想测试这个FooComponent:

<div>
  <slot :fn="internalFn" />
</div>

它是这样使用的(例如在ParentComponent中):

<FooComponent>
  <template slot-scope="slotProps">
    <BarComponent @some-event="slotProps.fn" />
  </template>
</FooComponent>

所以我想测试我的组件在从插槽props 调用这个"fn"时的react .我看到的最简单的方法是采用方法本身并调用它,如下所示:

cosnt wrapper = shallowMount(FooComponent, /* ... */)
wrapper.vm.methods.internalFn(/* test payload */)
expect(wrapper.emitted()).toBe(/* some expectation */)

但这被称为测试内部实现的反模式.所以我想通过传送到插槽中的prop fn来测试它,因为它也是某种组件接口,比如组件自己的prop.

但如何测试props 通过槽?我可以想象,只有在我测试ParentComponent个类似的东西时,它才会起作用:

const wrapper = shallowMount(ParentComponent, /* ... */)
const foo = wrapper.find(FooComponent)
wrapper.find(BarComponent).vm.$emit('some-event', /*...*/)
/* write expectations against foo */

但这感觉就像是FooComponent次测试,ParentComponent次内部测试

也许有更好的方法?

推荐答案

线下UPD:是我多年前给出的原始答案.今天我要说的是,其中一种方法已经足够好了:

  1. 不要测试slot方法,而是测试依赖它的面向用户的特性.首先try 手动测试,注意你是如何做的,然后try 编写一个类似的测试.例如,testing-library/vue美元

  2. 如果第一个选项太难做,试着想出一些假的测试组件.这个 idea 与我在问题中描述的非常相似

但这感觉就像是对FooComponent的测试,对ParentComponent的测试

但是不要使用ParentComponent,只需创建一些非常简单的内联组件(就在FooComponent.spec.js文件中),它使用带有插槽的组件.


Original answer that was given in 2020:

因为没有答案,所以我只分享我最终得到的结果.

我决定测试内部方法.这并不酷,但至少,因为我使用typescript,所以我有一个类型安全测试,如果我重命名或修改我测试的方法,它将失败,并出现明显的类型错误.看起来像这样:

import Foo from '@/components/foo/Foo.ts'
import FooComponent from '@/components/foo/Foo.vue'

/*...*/

cosnt wrapper = <Foo>shallowMount(FooComponent, /* ... */)

// notice that because I passed `Foo` which is a class-component, 
// I have autocomplete and type checks for vm.*
wrapper.vm.internalFn(/* test payload */)

expect(wrapper.emitted()).toBe(/* some expectation */)

Vue.js相关问答推荐

在VueJS中卸载元素之前是否应该删除JavaScript事件收件箱?

Vue Router中.getRoutes()获取的路由顺序优化建议

如何在FormKit中验证文本输入框中不能输入数字

Nuxt 和 Vite 有什么区别?

VueJS CKeditor5 上传图片

将props传递给设置时的VueJS 3组合API和TypeScript类型问题:类型上不存在属性 user用户

使用 vue-cli 遇到无法推断解析器错误

如何在 vue.js 中删除类

使用 Vue Router 设置页面标题

在 SPA VueJS 中全局声明 mapState 和 mapMutations

如何将 Nuxt.js 更新到最新版本

vue-test-utils:无法覆盖属性 $route,这通常是由于插件将该属性添加为只读值

我在 Nuxt 2.14.0 中运行的是什么版本的 Vue?

使用 vue-router 的默认子路由

基于媒体查询的vue绑定值

Vue 组件中的组件渲染函数中可能存在无限更新循环警告

模块构建失败:错误:没有给出解析器和文件路径,无法在 nuxtjs 中推断出解析器

如何在 JEST 测试中模拟全局 Vue.js 变量

如何在 Vue.js 插槽范围内传递方法

Vue js在列表中添加动态字段,删除和排序不起作用