Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a Vue component containing a Vuetify data table with slots

I'm trying to unit test a simple component with a nested v-data-table component. The page renders properly in the browser, but I can't seem to write a Jest test that works.

The issue seems to be with the template I'm using for the slot -- which I pulled directly off the documentation.

When I comment out the template with the v-slot attribute, the test executes fine.

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"
      }
    ]);
  });
});

Error message:

  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
like image 696
sp0gg Avatar asked May 06 '20 23:05

sp0gg


Video Answer


1 Answers

I ran into this same issue and found that if you wrap the v-data-table in a div, the test succeeds. For some reason shallowMount fails in Jest when the v-data-table is the root element of your template.

like image 187
Ryan King Avatar answered Sep 23 '22 03:09

Ryan King