单元测试:如何正确触发在vuex中调用函数的输入的触发事件?

时间:2020-10-28 12:04:29

标签: unit-testing vue.js vuex bootstrap-vue ts-jest

我有这个boots 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

1 个答案:

答案 0 :(得分: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();
 });