单元测试:如何在调用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";被调用";name";但结果测试表明:预期的呼叫数:>=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();
});

最新更新