unit-testing - 单元测试:如何在调用 vuex 中的函数的输入上正确触发触发事件?
问题描述
我有这个引导 vue 组件:
<b-form-input
v-model="currentUser.name"
placeholder="Name *"
name="name"
@input="checkSubmitStatus()"
></b-form-input>
方法中的 checkSubmitStatus 去调用 updateSubmitDisabled 我在另一个文件中的突变中:
methods: {
...mapMutations({
updateSubmitDisabled: "updateSubmitDisabled"
}),
checkSubmitStatus() {
const isDisabled = this.currentUser.name.length === 0;
this.updateSubmitDisabled(isDisabled);
}
}
这是 .spec.js 文件:
import { createLocalVue, mount } from "@vue/test-utils";
import Vue from "vue";
import Vuex from 'vuex';
import UserForm from "@/components/event-created/UserForm.vue";
import { BootstrapVue, BootstrapVueIcons } from "bootstrap-vue";
const localVue = createLocalVue();
localVue.use(BootstrapVue);
localVue.use(BootstrapVueIcons);
localVue.use(Vuex);
describe("UserForm.vue", () => {
let mutations;
let store;
beforeEach(() => {
mutations = {
updateSubmitDisabled: jest.fn()
};
store = new Vuex.Store({
state: {
currentUser: {
name: 'pippo',
}
},
mutations
});
})
it("should call the updateSubmitDisabled mutation", async () => {
const wrapper = mount(UserForm, { localVue, store });
const input = wrapper.get('input[name="name"]');
await Vue.nextTick();
input.element.value = 'Test';
await input.trigger('input');
await Vue.nextTick();
expect(mutations.updateSubmitDisabled).toHaveBeenCalled();
});
});
现在我只想测试是否在“名称”上调用了“updateSubmitDisabled”,但结果测试显示:预期的呼叫数:> = 1 收到的呼叫数:0
解决方案
我终于解决了:
it("should call the updateSubmitDisabled mutation", () => {
const wrapper = mount(UserForm, { localVue, store });
const input = wrapper.get('input[name="name"]');
input.element.dispatchEvent(new Event('input'));
expect(mutations.updateSubmitDisabled).toHaveBeenCalled();
});
推荐阅读
- javascript - 如何在悬停在不同文本上时多次更改图像
- excel - 如何将 x 个 0 添加到 COUNTIF MAX VLOOKUP 公式的结果
- python - 获取查询 sqlalchemy 中所有值的属性
- scala - 在 scala 2 中,可以使用宏或任何语言特性来重写所有子类中的抽象类型具体化机制吗?斯卡拉 3 怎么样?
- r - 如何使用 R 中另一个变量的分位数创建一个变量?
- nuxt.js - 使用 storyblok 和 nuxt 设置可视化编辑器
- html - 为什么我的弹性项目中 div 的高度如此之小?
- ios - 我们能否将 main.swift 文件重命名为 Main.swift(大写)
- vapor - 在 Fluent 迁移中为新的必填字段设置默认值
- php - Laravel API 覆盖默认 413 Payload Too Large 响应