使用Jest在Vue中测试按钮的触发单击不起作用

时间:2020-05-13 18:32:50

标签: unit-testing vue.js jestjs buttonclick

使用Jest在Vue中测试按钮的触发单击不起作用。 当我尝试在包装器中找到按钮时,测试通过,但是当我尝试触发时,单击同一按钮,因此将调用该方法,此方法将无效。

这是按钮的vue文件快照:

<v-btn @click="viewAppointment(appointment)" class="ma-2" dark small color="orange" id="view-appointment" data-viewAppointmentBtn>
  <v-icon left>mdi-eye</v-icon>
  <span>View</span>
</v-btn>

这是包含简单方法调用的js文件:

viewAppointment(appointment) {
  this.appointment = appointment;
  this.viewAppointmentDialog = !this.viewAppointmentDialog;
},

这是测试的.spec.js文件:

import './setup.js';
import CoachAppointmentsRequests from '../dashboard/coach/appointments/requests/overview/Overview.vue';
import {shallowMount, createLocalVue} from "@vue/test-utils";
import Vuex from "vuex";

const localVue = createLocalVue();
localVue.use(Vuex);

describe("CoachAppointmentsRequests", () => {

  let wrapper;
  let store;
  let actions;
  let state;
  let getters;

  const $route = {
    path: 'appointment/requests/:application_id',
    params: { application_id: 123 }
  }

  actions = {
    GET_USER_APPOINTMENTS: jest.fn()
  };
  state = {
    user_appointments: [ {id:1, date: 'May 20, 2020'} ],
    all_user_appointments: [ {id:1, date: 'May 20, 2020'} ],
  };
  getters = {
    user_appointments: state => state.user_appointments,
    all_user_appointments: state => state.all_user_appointments
  };
  store = new Vuex.Store({
    actions,
    getters,
    state,
  });

  const getUserAppointments = jest.fn(() => {
    return new Promise(resolve => {
      process.nextTick(() => {
        resolve({
          data: [
            { id:1, appointee_id:2}
          ]
        })
      })
    })
  });

  beforeEach(() => {
    wrapper = shallowMount(CoachAppointmentsRequests, {
      propsData: {},
      mocks: {
        $route,
      },
      stubs: {},
      methods: {
        getUserAppointments,
      },
      store,
      localVue,
    });
  });

  it('click on the view appointment button calls the viewAppointment method', () => {
    const viewAppointment = jest.fn();
    wrapper.setMethods({ viewAppointment })
    const viewAppBtn = wrapper.find('#view-appointment');
    viewAppBtn.trigger('click');
    expect(viewAppointment).toBeCalled();
  });
});

对于您在此问题上的帮助,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

Object处理程序不是在click之后立即调用,而是在下一个刻度中调用。但是,trigger()返回一个trigger()来解析组件更新的时间,因此您可以await调用结果,如docs example所示:

Promise