对包含带有插槽的Vuetify数据表的Vue组件进行单元测试

时间:2020-05-06 23:59:13

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

我正在尝试对带有嵌套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

1 个答案:

答案 0 :(得分:2)

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