typescript - 如何使用 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);
}
}
解决方案
这是我如何使它工作的:
组件测试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);
});
});
});
我希望我自己的回答能帮助别人,因为我花了很长时间才弄清楚这一切。
推荐阅读
- paypal - Paypal:抱歉,我们无法使用您选择的付款方式设置您的订阅。请尝试其他付款方式
- animation - 是否有可能在现代浏览器中获得一致的 apng 支持?
- javascript - 使用 plotly-js 绘制多个支持 extendTrace 的变量
- c++ - CRC4 INTERLAKEN 和 ITU 查找表生成
- vuejs2 - v-text-field 中的多个验证规则
- typescript - 对象的 TypeScript 类型,指定了一个属性类型,而所有其他属性类型都是不同的类型
- flutter - 无法在 VS Code 中调试颤振飞镖代码,未验证断点错误
- material-ui - 有条件地在 MUI 上添加样式属性
- javascript - 更改图像 src 后画布上的 Ionic 4 drawImage
- java - 如何遍历对象列表