Learn how to implement a global event bus in VueJS with this insightful article. Instead of the conventional method of using an event bus defined in a separate file, the article introduces an alternative approach:
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;
This new method involves attaching the global event bus to the main Vue instance directly:
// main.js
import Vue from 'vue';
Vue.prototype.$eventBus = new Vue(); // Using $eventBus instead of $eventHub
new Vue({
el: '#app',
template: '<App/>',
});
// or alternatively
import Vue from 'vue';
import App from './App.vue';
Vue.prototype.$eventBus = new Vue();
new Vue({
render: (h): h(App),
}).$mount('#app');
However, when it comes to unit testing, there seems to be confusion on how to test the global event bus created in this manner.
Even though there are existing questions on platforms like Stack Overflow regarding testing a global event bus, satisfactory solutions remain elusive.
Attempting suggestions such as using createLocalVue
as recommended in some responses didn't yield the desired outcomes:
it('should listen to the emitted event', () => {
const wrapper = shallowMount(TestingComponent, { localVue });
sinon.spy(wrapper.vm, 'handleEvent');
wrapper.vm.$eventBus.$emit('emit-event');
expect(wrapper.vm.handleEvent.callCount).to.equal(1);
});
The expected count was 0, while the actual was 1. Despite trying with asynchronous functions and $nextTick()
, success remained elusive.
In this example, tools like mocha
, chai
, and sinon
were used for illustration purposes. Inputs using different frameworks and libraries for testing are highly welcomed.
UPDATE on February 25th, 2020
After delving into the book "Testing Vue.js Applications" by Edd Yerburgh, author of @vue/test-utils
, some insights were gained, but testing the global event bus added as an instance property still remains a challenge.
A GitHub repository was set up with sample code following the principles outlined in the medium.com article. For the testing phase of this project, jest
was utilized for convenience.
Below is an outline of the code structure:
Discussing the challenges faced during unit tests, particularly focusing on the third test scenario in tests/unit/HelloWorld.spec.js
. How can one verify that a specific method is invoked when an event is emitted? Is it necessary to cover this behavior in unit tests?