Home » vue » Testing Vuejs EventBus

Testing Vuejs EventBus

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have been trying to figure this out for some time already, but I can not make it work! I found some examples on internet, but nothing solves it, every time I run my test I get:

 Expected number of calls: 1
 Received number of calls: 0

> 186 |        expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);

The component looks like this:

import {EventBus} from 'eventbus'
export default{
    data(){ return {}},
    mounted(){
        EventBus.$on('saveTerminal', function(){
             this.someOtherFunction()        
        })
    }
}

Event Bus file looks like this

import Vue from 'vue';
export const EventBus = new Vue();

The Test looks like this:

    const GlobalPlugins = {
         install(v) {
            v.prototype.EventBus = new Vue();
         },
     };
    //Vue.prototype.EventBus = new Vue(); <-- I tried this also, didn't do anything
    
    // Mounting component
    const $t = () => {}
    const params = { localVue, store, router,
        propsData: {
            isEdit: false
        },
        data(){
            return {
                loading: false,
                tabIndex: 1
            };
        },
        mocks:{
            $t,
            EventBus: {
                $on: jest.fn(),
                $off: jest.fn(),
                $emit: jest.fn()
            }
        },
     }
    
    const wrapper = shallowMount(MyComponent, params)
   describe('My component', () => { 
       it('Event bus', () => {
           wrapper.vm.EventBus.$emit('saveTerminal');
    
           expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);
        expect(wrapper.vm.EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
       });
    })
Answers:

You can use jest.mock() to mock the EventBus module. Your test would require() the module to access the mock, and then verify its $on was called:

import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

jest.mock('@/utils/EventBus')

describe('MyComponent.vue', () => {
  it(`listens to 'saveTerminal' upon mounting`, async () => {
    const { EventBus } = require('@/utils/EventBus')
    shallowMount(MyComponent)
    expect(EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
  })
})

demo