Patrick
Patrick

Reputation: 2195

How to test the contents of a dropdown list web-component with VueJS, typescript and jest

I'm trying to test the contents of a dropdown list implemented as a web component used in a VueJS application.

Specifically, I want to test if a given dropdown list contains items which are retrieved by an HTTP query (implemented in a vuex store) when the application's created() lifecycle hook is triggered.

The VueJS application is written in typescript and I use Jest as my testing framework.

My Vue component SearchBar.vue that I would like to test:

<template>
    <dropdown-web-component
        label="Applications"
        :options.prop="applications"
    />
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class SearchBar extends Vue {
    get applications() {
        return this.$typedStore.state.applications;
    }
    created() {
        // the http call is implemented in the vuex store
        this.$store.dispatch(Actions.GetApplications);
    }
}

Upvotes: 0

Views: 1637

Answers (1)

Patrick
Patrick

Reputation: 2195

Here is how I made it work:

The SearchBar.spec.ts test for the component:

import Vuex, { Store } from "vuex";
import { shallowMount, Wrapper } from "@vue/test-utils";
import SearchBar from "@/components/SearchBar.vue";
import { Vue } from "vue/types/vue";

describe('SearchBar', () => {
    let actions: any;
    let store: Store;
    let state: any;

    beforeEach(() => {
        const applications = ['applicationId1', 'applicationId2', 'applicationId3'];

        actions = {
            GET_APPLICATIONS: jest.fn()
        };
        state = {
            applications
        };
        store = new Vuex.Store({
            modules: {
                users: {
                    actions,
                    state
                }
            }
        });
    });

    it('should dispatch the GET_APPLICATIONS vuex store action when created', () => {
        shallowMount(SearchAndFilterBar, { store });

        expect(actions.GET_APPLICATIONS).toHaveBeenCalled();
    });

    describe('Applications dropdown', () => {
        it('should render a dropdown with applications', () => {
            const wrapper = shallowMount(SearchAndFilterBar, {
                store
            });
            const filter: Wrapper<Vue> = wrapper.find('dropdown-web-component');
            // without the cast to any, TS will not be able to find vnode
            expect((filter as any).vnode.data.domProps.options.length).toEqual(3);
        });
    });
});

I hope my own answer helps someone out as well as it took me quite some time to figure all of this out.

Upvotes: 1

Related Questions