【问题标题】:Unit testing a Vue component containing a Vuetify data table with slots单元测试包含带有插槽的 Vuetify 数据表的 Vue 组件
【发布时间】:2020-08-22 03:25:19
【问题描述】:

我正在尝试使用嵌套的 v-data-table 组件对简单组件进行单元测试。该页面在浏览器中正确呈现,但我似乎无法编写有效的 Jest 测试。

问题似乎与我用于插槽的模板有关——我直接从文档中提取了该模板。

当我用v-slot 属性注释掉模板时,测试执行良好。

People.vue:

<template>
  <v-data-table
    :headers="headers"
    :items="people"
    disable-pagination
    disable-sort
    disable-filtering
    hide-default-footer
    :loading="!people"
  >
    <template v-slot:item.id="{ item }">
      <v-icon>
        mdi-link-variant
      </v-icon>
      <router-link
        :to="{ name: 'assignments', query: { assignee_id: item.id } }"
        >Link</router-link
      >
    </template>
  </v-data-table>
</template>

<script>
export default {
  name: "People",
  data: () => ({
    headers: [
      {
        text: "Name",
        value: "first_name"
      },
      {
        text: "Assignment link",
        value: "id"
      }
    ]
  }),
  props: {
    people: {
      type: Array,
      required: true
    }
  }
};
</script>

People.spec.js:

import { shallowMount } from "@vue/test-utils";
import People from "@/components/People.vue";

function getMountedComponent(Component, propsData) {
  return shallowMount(Component, { propsData });
}

const propsData = {
  people: [{ id: 1 }]
};
describe("headers", () => {
  it("contains name and assignment", () => {
    expect(getMountedComponent(People, propsData).vm.headers).toEqual([
      {
        text: "Name",
        value: "first_name"
      },
      {
        text: "Assignment link",
        value: "id"
      }
    ]);
  });
});

错误信息:

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
    [Vue warn]: Error in render: "TypeError: Cannot read property 'item' of undefined"

    found in

    ---> <VDataTable>
           <People>
             <Root>

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
    TypeError: Cannot read property 'item' of undefined

【问题讨论】:

  • 您找到解决方案了吗?
  • 有完全相同的问题。你找到解决办法了吗?
  • 没有解决办法。来自 Vuetify Discord 的人建议使用 mount 而不是 shallowMount,对我来说,这违背了目的。
  • 请参阅下面 Ryan King 的回答。这对我有用。

标签: javascript vue.js ecmascript-6 jestjs vuetify.js


【解决方案1】:

我遇到了同样的问题,发现如果将v-data-table 包装在div 中,则测试成功。出于某种原因,当 v-data-table 是模板的根元素时,shallowMount 在 Jest 中失败。

【讨论】:

  • 将 v-data-table 包装在一个 div 中对我有用。应标记为正确答案。
猜你喜欢
  • 2020-08-02
  • 2021-01-15
  • 2019-12-25
  • 2020-01-21
  • 2020-12-22
  • 2017-11-19
  • 2019-04-18
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多