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
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With