Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error:

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

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

Here is how the component is structured:

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

The Event Bus file appears as follows:

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

This is what the test code looks like:

    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))
       });
    })

Answer №1

One approach is to utilize the jest.mock() method for mocking the EventBus module. In your test case, you would need to require() the module in order to access the mock and then verify if its $on function 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))
  })
})

Check out the demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize React MaterialUI's ExpansionPanelSummary by incorporating a counter to a specific div id

I am in need of a feature that will automatically increment a counter in the div id every time the render function is invoked. The main goal is to ensure that each div has a unique identifier. Below is the current render function implementation - render ...

I'm getting an error message like, "Feature flag __VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined. Can you please help

Ever since upgrading my vue.js to version 3.4.4, I've been encountering a new warning in the browser console: The feature flag VUE_PROD_HYDRATION_MISMATCH_DETAILS is not explicitly defined. As I am running the esm-bundler build of Vue, it requires th ...

Utilize Jquery to easily interact with RadComboBoxes

Is there a way to capture all RadComboBoxes change events in JQUERY for ASP.NET? $("input[type='text']").Change(function() { alert('changed'); }); In this example, I am specifying the input type as "text" because RadComboBoxes hav ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Tips for uploading images using Rails-Api, Vue.js, Cloudinary, and Attachinary

In my experience working with server-rendered Rails applications, I have relied on Cloudinary and Attachinary for uploading images and files to an external server and linking them to my data models. As I transition to using Vue.js with Rails-API more freq ...

Effortlessly adjust the top margin of the div element

I have been attempting to smoothly move a div (circle), but I'm facing difficulties. The div instantly jumps to the final position instead of moving smoothly. In an effort to simulate the process of a ball falling, I tried using the animate method wi ...

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...

Tips on transferring a Rails variable to Ajax

Struggling to integrate a progress bar (Javascript) into my Ruby on Rails application, I am facing difficulties in passing values from the controller to JS for updating the bar. In my initial attempt, I used a basic global variable ($count), but it remain ...

What is the best way to halt the execution of content scripts in the active tab?

I am currently developing a Google Chrome Extension and have come across a bug that I am struggling to fix on my own. The extension works as intended when switching to Youtube's Dark Mode on a single tab. However, if you are on Youtube and open a new ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

The most recent release of Chrome (Version 47.0.2526.80 m) introduces an intriguing feature. When using navigator.webkitGetUserMedia, the returned stream now lacks a

I recently encountered a problem with my code that used to access the camera on Chrome browser and release it after use. Here's the code snippet: Starting the Camera: navigator.webkitGetUserMedia($scope.options.videoObj, function (stream) { $sco ...

Capturing and saving detailed hand-drawn artwork in high resolution

Is there a cutting-edge solution available for capturing hand-drawn sketches (from a tablet, touch screen, or iPad-like device) on a website using JavaScript and saving it on the server side? Essentially, I am looking for a mouse drawing canvas with a hig ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and I’m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...

What is the best way to condense a repetitive method declaration and make it more concise?

I'm facing a situation where I have declared similar const values. Here's my current setup... import React from 'react' function Component_a() { const x = 5; const y = 10; const image_a = [...Array(x)].map((e, i) => ...

Is there a way to identify a change in the URL using JQuery?

My goal is to clear the localStorage when a user navigates to a different page. For instance, if I am currently on . When the user goes to the URL, , I want to clear the localStorage. This is my script using JQuery. $(window).unload(function(){ if ...

When you click, transfer a single item from one array to another and modify the text according to the items in the array

How can I dynamically update a shopping cart feature on my website when a user clicks on the "addtocart" button? I want to create functionality where clicking on the button adds the corresponding product to the cart array, and updates the cart amount displ ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...

Guide on transferring numerous files (50k+) from a folder to AWS S3 using node.js

Currently, my Node.js API on a Windows machine is generating numerous XML files that are later sent to an S3 bucket. The quantity of files sometimes surpasses 50k. For the uploading process, I am utilizing the aws-sdk package. Essentially, I iterate throu ...