【问题标题】:Testing v-slots with v-for - Jest / Vue使用 v-for 测试 v-slots - Jest / Vue
【发布时间】:2019-08-12 18:36:12
【问题描述】:

我正在尝试弄清楚如何测试我的组件中包含 v-slot。 组件模板结构:

Grid.vue

<div> 
   <v-slot>
</div>

当我称之为它时,它是这样的:

<Grid>
   <Column v-for="(element, index) in list" :key=index /> 
</Grid>

到目前为止,我已经知道了:

import { mount } from '@vue/test-utils';
import Grid from '~/components/Grid';
import GridColumn from '~/components/Column';

const columns = [
    {
        id: 'col1',
    },
    {
        id: 'col2',
    },
];

describe('Grid.vue', () => {
    const columnWrapper = {
        // render(h) {
        //     return columns.map(function (item) {
        //         return h('Column', item.id) })
        // }
        render(h) {
            return h(Column, { props: { index: 1, column: columns[0] } });
        }
    };

    const wrapper = mount(Grid, {
        slots: { columnWrapper }
    });
});

我确实为Grid 编写了两种渲染槽的方法。带有return h(Column.... 的第二个仅创建一列。我怎样才能呈现列 = 模型列表的列数?第一个选项/评论我不确定如果我写得好 - return h('Column' .... - 那可能是错误的。

当我控制台日志wrapper.vm.$el.children HTMLCollection 是空的。列未添加到 Grid。有谁知道我做错了什么?

【问题讨论】:

  • v-slot 是新指令,不是内置组件

标签: javascript vue.js jestjs


【解决方案1】:

实际上,不清楚您想通过该测试实现什么,它看起来很复杂。 如果您只想测试 Grid 组件或使用一些插槽对其进行初始化,我建议您编写一些可读的内容并避免使用其他组件:

// example
const wrapper = mount(Grid, {
    slots: {
       default: columns.map(c => `<div class="foo">${c.id}</div>`)
    }
});

expect(wrapper.findAll('.foo').length).toBe(2)

如果你想测试这部分:

// for example, GridUsage.vue
<Grid>
   <Column v-for="(element, index) in list" :key=index /> 
</Grid>

所以只测试存在这种用法的组件,Grid.vue 不负责

// example part of test file
const columns = [
   {
      id: 'col1',
   },
   {
      id: 'col2',
   },
];
const wrapper = mount(GridUsage, { propsData: { list: columns  } });
expect(wrapper.findAll(Column).length).toBe(2)

当然,Column.vue 应该有一个单独的测试

文档:Vue Test Utils-Mounting Options-Slots

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 2019-12-20
    • 2018-06-13
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多