首页 > 解决方案 > 如何使用 VueJS、typescript 和 jest 测试下拉列表 web 组件的内容

问题描述

我正在尝试测试作为 VueJS 应用程序中使用的 Web 组件实现的下拉列表的内容。

具体来说,我想测试给定的下拉列表是否包含在created()触发应用程序的生命周期挂钩时由 HTTP 查询(在 vuex 存储中实现)检索的项目。

VueJS 应用程序是用 typescript 编写的,我使用 Jest 作为我的测试框架。

SearchBar.vue我想测试的 Vue 组件:

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

标签: typescriptvue.jsjestjsweb-component

解决方案


这是我如何使它工作的:

组件测试SearchBar.spec.ts

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

我希望我自己的回答能帮助别人,因为我花了很长时间才弄清楚这一切。


推荐阅读