Reputation: 21
I am currently writing tests for my Vue application. I have a button which calls a logout function. I just want to test if the function gets called when the button gets clicked.
I have tried to mock the function with jest.fn() but i cant get it to work. I also tried to actually trigger the method and put a console.log in the method but that log did not get called. 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.
Upvotes: 2
Views: 11926
Reputation: 3285
When using shallowMount
the methods of component should be stubbed. You can achieve this while creating the wrapper or by using 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();
});
Upvotes: 2