I am currently facing a challenge with testing a set of parent and child Vue components. The child component emits an event that is handled by the parent component. I want to verify that the custom event is handled correctly, but I've hit a roadblock.
Below is the code snippet for the Parent.vue file:
<template>
<div id="app" class="container">
<!-- phonebook -->
<ChildComponent
class="row mt-4"
@customEvent="val => customEventHandler(val)"
></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue'
export default {
name: 'App',
components: {
ChildComponent,
},
data() {
return {
test: [1, 2, 3, 4]
};
},
methods: {
customEventHandler(id) {
// removes item `id` from the `test` array
this.test = this.test.filter((item) => item !== id);
},
}
};
</script>
I have attempted to write tests for this scenario in the Parent.spec.js file, but unfortunately, they are failing. Here is one of the tests:
import { mount, shallowMount } from "@vue/test-utils";
import Parent from '../../src/Parent.vue';
import ChildComponent from '../../src/components/ChildComponent.vue';
describe('Testing the customEvent event', () => {
beforeEach(() => {
parent = mount(Parent, {
data() {
return {
test: [1, 2, 3, 4]
};
},
});
});
it('should trigger the customEventHandler method', async() => {
const spy = jest.spyOn(parent.vm, 'customEventHandler');
await parent.findComponent(ChildComponent).trigger('customEvent', 2);
expect(spy).toHaveBeenCalled();
})
})
Even though I have also tried other variations of tests, such as verifying the arguments passed to the spy or checking for side effects caused by the customEventHandler method, all of them seem to fail. It feels like the event isn't being triggered at all, or perhaps I'm attempting something that's not feasible.
Is there a recommended approach to properly test a parent component's handling of events emitted by its child component?