Guide to correctly setting up the b-table component in vue-test-utils

Currently, I am utilizing the buefy css library in conjunction with the vue.js framework.

The challenge I am facing involves unit testing my vue component (Foo), which includes the b-table component from buefy:

<b-table :data="foo" class="container" style="width: 50%">
        <b-table-column v-slot="props">
            <b-icon
                pack="fas"
                icon="times"
                class="is-clickable"
                @click.native="doSomething(props.row)"
            ></b-icon>
        </b-table-column>
</b-table>

Take note of the embedded b-icon

Within the Foo.spec.js test file, my objective is to mount the component using shallowMount from vue-test-utils:

import Buefy from "buefy";
import { shallowMount, createLocalVue } from "@vue/test-utils";
import Foo from './Foo.vue'

const localVue = createLocalVue();
localVue.use(Buefy);

const wrapper = shallowMount(Foo, {
    localVue,
});

Subsequently, I intend to utilize the returned wrapper to interact with the b-icon component which should be nested within the table column.

const icon = wrapper.find('.is-clickable')

icon.vm.$emit('click')

However, I encounter an error:

TypeError: Cannot read property '$emit' of undefined

Upon inspection, the b-icon seems to be absent within the wrapper as confirmed by wrapper.html():

<b-table-stub data="[object Object],[object Object]" columns="" headercheckable="true" checkboxposition="left" isrowselectable="[Function]" isrowcheckable="[Function]" checkedrows="" mobilecards="true" defaultsortdirection="asc" sorticon="arrow-up" sorticonsize="is-small" sortmultipledata="" currentpage="1" perpage="20" showdetailicon="true" paginationposition="bottom" rowclass="[Function]" openeddetailed="" hasdetailedvisible="[Function]" detailkey="" detailtransition="" total="0" filtersevent="" showheader="true" class="container" style="width: 50%;">
      <b-table-column-stub visible="true" thattrs="[Function]" tdattrs="[Function]"></b-table-column-stub>
</b-table-stub>

The disappearance of b-icon is perplexing.

Attempting a full mount via mount does not provide a solution either:

<div class="b-table container" style="width: 50%;">
      <!---->
      <!---->
      <!---->
      <div class="table-wrapper has-mobile-cards">
        <table class="table">
          <!---->
          <tbody>
            <tr draggable="false" class="">
              <!---->
              <!---->
              <!---->
            </tr>
            <transition-stub name="">
              <!---->
            </transition-stub>
            <!---->
            <tr draggable="false" class="">
              <!---->
              <!---->
              <!---->
            </tr>
            <transition-stub name="">
              <!---->
            </transition-stub>
            <!---->
            <!---->
          </tbody>
          <!---->
        </table>
        <!---->
      </div>
      <!---->
</div>

What steps should be taken to access the data / components nested within the table columns?

For additional information, here are the respective links to the b-table documentation and source code: Documentation and Source Code

Answer №1

To make use of shallowMount and stub the component b-table-column yourself, follow this example:

const BTableColumnStub = {
  template: <span class="b-table-column-super-stub"><slot name="props"></slot></span>
}

const wrapper = shallowMount(Foo, {
  localVue,
  stubs: {
    BTableColumn: BTableColumnStub  
  }
});

The component BIcon in your component is passed as a named slot props. By default, Jest's stubbing only stubs the component without considering slots. This method should help to render BIcon correctly.

Additionally, to trigger a click event, make sure to use await icon.trigger('click') instead of icon.vm.$emit('click'). If you need to test an event listener, you can also call wrapper.vm.$emit('your-event'). It's important to emit the event on the component that is listening to it, not the one that would emit the event.

Answer №2

When working with b-table components, consider using mount instead of shallowMount to more effectively render the table along with its child components.

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

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

Encountering a CssSyntaxError after upgrading from Webpack 3 to 4

When I recently updated webpack from version 3 to 4, I encountered a CssSyntaxError. My frontend setup involves using Vue with webpack and the error message looked like this: [./node_modules/css-loader/dist/runtime/api.js] 2.35 KiB {mini-css-extract- ...

Unable to execute AJAX POST request

https://i.stack.imgur.com/JqG7c.pngI have a JSON dataset like the one below: [ { "Password": "tedd", "Username": "john", "status": true } ] I need to consume this data using a POST method <label for="Username">Username:</label& ...

Using Ajax to seamlessly replace content with a smooth fade effect

Is it possible to add a fade effect to the code below, where the content of "demo" div is replaced with the content of "newpage.html"? <button onclick="loadDoc()">Click here</button> function loadDoc() { var xhttp = new XMLHttpRe ...

Executing a Cron Job several times daily, each and every day

This is my current code snippet: const CronJob = require('cron').CronJob; new CronJob({ cursoronTime: '* * * * *', // every minute onTick: async function() { console.log(&ap ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

Taking a Breather with mywindow.print()

I'm currently utilizing a fantastic printing script that I found: <script type="text/javascript"> function PrintElem(elem) { Popup($(elem).text()); } function Popup(data) { var mywindow = window.ope ...

Obtain information about a div element while scrolling

Looking to enhance my social feed page by adding a view count feature for each post. The challenge is figuring out how to keep track of views as the user scrolls down the page. Any suggestions? ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Having trouble getting the toggle menu to work using Jquery?

I am trying to create a toggle menu using jQuery on this particular page: . The menu is located in the top right corner and I want it to appear when someone clicks on the "Menu ☰" button, and then disappear when clicked again (similar to this website: ). ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

Is there a way to develop a login form that retrieves information from a Google Sheet database?

Please help me with a solution. I have developed a registration form which effectively saves users' information in a Google Sheet. However, now I am yearning to create a login form that verifies the stored data and redirects the user to a different pa ...

Utilize dynamic inline styling to pass asset image paths as background images in Nuxt.js

I am in the process of developing a Nuxt.js application and I have a requirement to dynamically set the background image of an element using images from the assets folder. Here is what I have implemented: <template> <div> <div v ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

Use .empty() method to remove all contents from the tbody element after creating a table

Currently, I am working on a project where I am creating a drop-down list to assist users in selecting media and ink for their printers. The goal is to then generate a table displaying the selected results. While I have managed to successfully generate the ...