import { mount } from '@vue/test-utils';
import ParentComponent from '@/components/ParentComponent.vue';
import ChildComponent from '@/components/ChildComponent.vue';
describe('ParentComponent', () => {
it('emits a custom event when calling a method in ChildComponent', async () => {
const wrapper = mount(ParentComponent);
const childComponent = wrapper.findComponent(ChildComponent);
// Mock the emitted event
const emittedEvent = jest.fn();
wrapper.vm.$on('customEvent', emittedEvent);
// Trigger the method in ChildComponent that emits the event
await childComponent.vm.emitCustomEvent();
// Check if the event was emitted
expect(emittedEvent).toHaveBeenCalledWith(/ Any expected arguments /);
});
});
<!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent @customEvent="handleCustomEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
methods: {
handleCustomEvent(payload) {
// Handle the emitted event from ChildComponent
},
},
};
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<!-- Your component content -->
<!-- Trigger the method that emits the custom event -->
<button @click="emitCustomEvent">Trigger Event</button>
</div>
</template>
<script>
export default {
methods: {
emitCustomEvent() {
this.$emit('customEvent', / Any data you want to pass /);
},
},
};
</script>