在Vue中使用Jest测试按钮上的触发器点击不工作。

问题描述 投票:0回答:1

在Vue中,使用Jest测试一个按钮上的触发点击不能工作。当我尝试在包装器中找到按钮时,测试通过了,但是当我尝试在同一个按钮上触发点击,使一个方法被调用时,它不能工作。

这里是按钮的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();
  });
});

请您协助解决这个问题,我将感激不尽。

unit-testing vue.js jestjs buttonclick
1个回答
0
投票

click 处理程序后没有立即调用 trigger(),而是在下一个tick中调用。然而, trigger() 返回一个 Promise 当组件更新时就会被解析,所以你可以用 await 调用的结果,如在 文档范例:

it('clicked it', async () => {
  // ...
  await viewAppBtn.trigger('click')
  expect(viewAppointment).toBeCalled()
})
© www.soinside.com 2019 - 2024. All rights reserved.