简体   繁体   English

Jest Test 中的触发事件不调用 Method

[英]Trigger event in Jest Test does not call Method

I am currently writing tests for my Vue application.我目前正在为我的 Vue 应用程序编写测试。 I have a button which calls a logout function.我有一个调用注销 function 的按钮。 I just want to test if the function gets called when the button gets clicked.我只想测试单击按钮时是否调用了 function 。

I have tried to mock the function with jest.fn() but i cant get it to work.我试图用 jest.fn() 模拟 function 但我无法让它工作。 I also tried to actually trigger the method and put a console.log in the method but that log did not get called.我还尝试实际触发该方法并将 console.log 放入该方法中,但该日志没有被调用。 What am I doing wrong?我究竟做错了什么?

this is my wrapper setup:这是我的包装器设置:

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();
    });

I expect the mocked method to be called but actually i get an error saying:我希望调用模拟方法,但实际上我收到一条错误消息:

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

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

When using shallowMount the methods of component should be stubbed.当使用shallowMount时,组件的方法应该被存根。 You can achieve this while creating the wrapper or by using setMethods() .您可以在创建包装器时或使用setMethods()来实现此目的。

You only need to change your unit test:您只需要更改单元测试:

  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();
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM