The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook

Here is a snippet of mycomponent.vue:

<template>
  <div>
    <b-button @click="add">open modal</b-button>
    <b-modal static lazy id="modal-detail" @ok="save">
      <b-form-input v-model="fooName"></b-form-input>
    </b-modal>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import { RestClient } from "./RestClient";

@Component({ name: "fooController" })
export default class FooController extends Vue {
  public fooName = "";
  public add(): void {
    this.$root.$emit("bv::show::modal", "modal-detail");
  }
  public save(): void {
    console.log("in save method");
    RestClient.create(this.fooName);
  }
}
</script>

This is how RestClient.ts is structured:

export class RestClient {
  static create(payload: string) {
    return payload;
  }
}

And here is a glimpse of the test:

import { createLocalVue, mount } from "@vue/test-utils";
import BootstrapVue from "bootstrap-vue";
import MyComponent from "./mycomponent.vue";
import { RestClient } from "./RestClient";

jest.mock("./RestClient.ts", () => ({
  RestClient: {
    create: jest.fn(() => {
      return {};
      //   return Promise.resolve({});
    })
  }
}));

describe("component test", () => {
  const localVue = createLocalVue();
  localVue.use(BootstrapVue);

  it("should call the create method on the REST client when ok-ing the modal", (done) => {
    const wrapper = mount(MyComponent, {
      attachToDocument: true,
      localVue
    });
    expect(wrapper.isVueInstance()).toBe(true);

    // triggering the open modal button
    wrapper.find("button").trigger("click");
    const modal = wrapper.find("#modal-detail");

    modal.vm.$emit("ok");

    return wrapper.vm.$nextTick().then(() => {
      expect(RestClient.create).toBeCalled();
      return wrapper.vm.$nextTick().then(done);
    });
 });
});

I am emitting the ok event on the modal directly and expecting to see the console.log statement in the save-method executed. However, I cannot find it in the terminal while running the test.

Hence, the RestClient.create method is not being invoked as expected. Why is that happening?

Answer №1

@ok represents a specialized Vue event, distinct from standard browser DOM events. Using the .prevent modifier with custom Vue events will not yield the expected result.

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

The code snippets in the Vue3 documentation are quite peculiar

As I peruse the Vue 3 documentation, I notice a recurring pattern in how example code is presented for components: Vue.createApp({}) However, my experience with Vue 3 has been different. Instead of the above syntax, I simply use: <script> export d ...

Icons in React are used to visually represent various actions

I am facing an issue with the React icons I imported on my personal website. They are not displaying at all. Despite reinstalling React Icons multiple times, with and without --save, the problem persists. I have thoroughly checked both the node_modules dir ...

Maintaining the aspect ratio of images in Bootstrap Carousel: A complete guide

Using the default carousel from Bootstrap template has been working well for me. However, I've encountered an issue where resizing the browser window distorts the image aspect ratio by squishing it horizontally. I've tried various solutions to m ...

Check to see if a key exists within the entire JSON using jQuery

I'm struggling with checking if a specific key is contained in my JSON data array. I want to add a class or perform an action if the key is present, otherwise do something else. I've tried using inArray and hasOwnProperty but can't seem to g ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

Angular 2's abstract component functionality

What are the benefits of utilizing abstract components in Angular 2? For example, consider the following code snippet: export abstract class TabComponent implements OnInit, OnDestroy {...} ...

Vue snapshot testing is encountering a failure with the error message "TypeError: Cannot read property of undefined"

Everything seems to be working fine with the component on the page without any errors. Storybook is also functioning well, but the problem lies in the unit test. import { mount } from '../../vue'; import { createLocalVue } from '@vue/test-u ...

How can I transform this imperative reducer into a more declarative format using Ramda?

I am currently working with a reducer function that aggregates values in a specific way. The first argument is the aggregated value, while the second argument represents the next value. This function reduces over the same reaction argument, aggregating th ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

How come my HTML form keeps refreshing instead of displaying an alert after submission, even though I've included onsubmit="return false"? Additionally, it seems to be throwing an error

Why is this basic HTML and JavaScript code not functioning properly? Instead of alerting once the form is submitted, it refreshes the page and throws an error. It has also been reported to sometimes throw a CORS error when using 'module' as scri ...

Utilize middleware nesting in Express.js

I am interested in implementing middleware to validate requests based on a RAML file. Below is an outline of my current code: // dependencies let resources = require('osprey-resources'); let errorHandler = require('request-error-handler&apo ...

Performing String formatting in JavaScript using an array

I've been utilizing the stringformat library to format strings in my node.js applications. var stringFormat = require('stringformat'); stringFormat.extendString(); In my current project, I'm attempting to pass an array of parameters a ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

Mastering the art of constraining TypeScript function parameters using interface properties

Hey there, I've been exploring ways to restrict a function parameter so that it only accepts "strings" related to interface properties, similar to what I achieved in the validate fields function: Please note: The TypeScript code provided here is simp ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Tips on placing custom loading components in Nuxt/Vue applications

I recently used nuxt and followed a helpful guide on creating a custom loading component. You can find the instructions here While the custom loader does work, I noticed that it appears in the same position as the original nuxt loader bar: https://i.stac ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

Error Handling with Firebase Cloud Firestore and State Management in Vue using Vuex (firebase.firestore.QuerySnapshot)

Upon examining the code, I noticed an issue with docChanges. It seems to be a function, but when I try to use docChanges().doc.data().userId, I encounter the error message: store.js?3bf3:21 Uncaught TypeError: Cannot read property 'doc' of undefi ...

What is the best way to pass multiple variables to a PHP file with AJAX using a GET request?

Can you help me figure out how to send both an I.D. value and a name value to a php file using ajax? Currently, I am successfully sending just the I.D. variable, however, when I attempt to add the name variable, the function stops working. The code that w ...