在Jest Test中触发事件不会调用Method

时间:2019-10-14 11:54:55

标签: javascript vue.js triggers jestjs vue-test-utils

我目前正在为Vue应用程序编写测试。我有一个调用注销功能的按钮。我只想测试单击按钮时是否调用了函数。

我试图用jest.fn()模拟该函数,但是我无法使其正常工作。我还尝试实际触发该方法,并将console.log放入该方法中,但未调用该日志。我在做什么错了?

这是我的包装器设置:

let wrapper;

beforeEach(() => {
    Vue.use(Vuetify);
    Vue.prototype.$router = new VueRouter();
    wrapper = shallowMount(Navigation);
});

afterEach(() => {
    wrapper.destroy();
});

it('should call logout function on button click', function() {
        let submitLogoutMock = jest.fn();
        wrapper.vm.submitLogout = submitLogoutMock;

        wrapper
            .find('#logout-button')
            .trigger('click');

        expect(submitLogoutMock).toHaveBeenCalled();
    });

我希望模拟方法能够被调用,但实际上我得到一个错误提示:

Error: expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called, but it was not called.

1 个答案:

答案 0 :(得分:0)

使用shallowMount时,应该对component的方法进行打桩。您可以在创建包装器时使用setMethods()

您只需要更改单元测试:

  it('should call logout function on button click', () => {
    const submitLogoutMock = jest.fn();
    wrapper.setMethods({ submitLogout: submitLogoutMock });

    wrapper.find('#logout-button').trigger('click');

    expect(submitLogoutMock).toHaveBeenCalled();
  });