unit-testing - Vue 如何使用 slot 和 slot-props 测试组件

标签 unit-testing vue.js testing frontend vue-test-utils

我想测试这个FooComponent:

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

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

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

因此,我想测试我的组件对从 slot Prop 调用此“fn”时的 react 。我看到的最简单的方法是获取方法本身并调用它,就像这样:

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

但这是众所周知的关于测试内部实现的反模式。所以我想通过传递到插槽中的 Prop fn 来测试它,因为它也是某种组件接口(interface),比如组件自己的 Prop 。

但是如何测试插槽中传递的 Prop ?我可以想象它只有在我测试 ParentComponent 类似的东西时才会起作用:

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

但这感觉就像在 ParentComponent 测试中测试 FooComponent

也许有更好的方法?

最佳答案

我参加聚会有点晚了,但我遇到了同样的问题。我从实际的 Vue 测试中得到了一些提示,虽然与我们相比,他们测试的内容更抽象,但它确实有所帮助。

这是我想出的:

import { shallowMount } from '@vue/test-utils';
import Component from 'xyz/Component';

let wrapperSlotted;

describe('xyz/Component.vue', () => {
  beforeAll(() => {
    wrapperSlotted = shallowMount(Component, {
      data() {
        return { myProp: 'small' }
      },
      scopedSlots: {
        default: function (props) {
          return this.$createElement('div', [props.myProp]);
        }
      },
    });
  });

  it('slot prop passed to a scoped slot', () => {
    let text = wrapperSlotted.find('div').text();
    expect(text).toBe('small'); // the value of `myProp`, which has been set as the text node in the slotted <div />
  });
});

所以最主要的是我为 scopedSlots 使用了渲染函数。

希望对某人有所帮助:)

关于unit-testing - Vue 如何使用 slot 和 slot-props 测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56492371/

相关文章:

testing - 如何在 testcafe 命令行中提供嵌套文件夹路径?

testing - 如何在特定方法中防止@Rollback?

c# - 将构造函数参数传递给 Nunit 基类

python - Karate 可以与pycharm一起使用吗?

vue.js - 如何监听在 vue js 中以编程方式创建的子事件?

laravel - 如何在 vuejs 中禁用按钮

c# - 在 C# 中测试电子邮件是否从外部系统发送

c# - 在 asp.net mvc 3 中登录的单元测试

unit-testing - 如何使用php单元测试多组数据?

javascript - Vue.js + 元素用户界面 : Content editable on el-table's rows