Search code examples
unit-testingvue.jsjestjsvue-test-utilsbootstrap-vue

vue.js unit test v-slot with function call


I use bootstrap-vue for the vue.js css framework and decided to test the desired component. This component uses b-table and has a v-slot with a call function.

<template>
    <b-table
        striped
        bordered
        :items="items"
        :fields="$t('pages.events.show.users.fields')"
    >
        <template v-slot:cell(name)="{ item }">
            <b-avatar :src="item.avatar" class="mr-2" />
            <span v-text="item.name" />
        </template>
    </b-table>
</template>

and I'm writing a simple test for this component:

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

/* #region  Test setup */
const factory = () => {
    return shallowMount(EventUsersTable, {
        mocks: {
            $t: jest.fn()
        },
        stubs: {
            BTable: true
        }
    });
};
/* #endregion */

describe("EventUsersTable.vue", () => {
    let wrapper;
    beforeEach(() => (wrapper = factory()));

    test("should render component", () => {
        expect(wrapper.html()).toMatchSnapshot();
    });
});

and i have error with this content: [Vue warn]: Error in render: "TypeError: Cannot read property 'item' of undefined"

for write test for this component i need fix this problem.

And I have a problem with the vue unit test document, they are very limited and with few examples. If anyone knows a source that has more examples and scenarios for vue language tests, thank you for introducing it.


Solution

  • After inquiring, I came up with a solution that, using mount and adding the main component, was able to solve my problem.

    import { mount } from "@vue/test-utils";
    import { BTable } from "bootstrap-vue";
    import EventUsersTable from "./EventUsersTable.vue";
    
    /* #region  Test setup */
    const factory = () => {
        return mount(EventUsersTable, {
            mocks: {
                $t: jest.fn()
            },
            stubs: {
                BTable
            }
        });
    };
    /* #endregion */
    
    describe("EventUsersTable.vue", () => {
        let wrapper;
        beforeEach(() => (wrapper = factory()));
    
        // FIXME: fix this bug for render component
        test("should render component", () => {
            expect(wrapper.html()).toMatchSnapshot();
        });
    });