Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows:

import vue from "vue";
import { render } from "@testing-library/vue";
import LibBtn from "./LibBtn.vue";

test('render LibBtn', () => {
    const { debug } = render(LibBtn);
    debug();
});

Here is the component related to this test:

<template>
       <!-- ... -->
            <slot>
                <LibIcon
                    v-if="icon"
                    :class="iconClass"
                    :icon="icon" />
            </slot>
            <LibIcon
                v-if="caret"
                class="text-tiny ml-1"
                :icon="['far', 'chevron-down']" />
        <!-- ... -->
</template>
<script setup>
import { computed } from 'vue';
import { useComputedVariant } from '@/composables/useTheme';

const props = defineProps({
    type: { type: String, default: 'button' },
    tag: { type: String, default: 'button' },
//... 
</script>

The test passed successfully but there was one warning:

  [Vue warn]: Failed to resolve component: LibIcon                                                                                                                                                                     
  If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.             

    at <Anonymous ref="VTU_COMPONENT" >                                                                                                                                                                              
    at <VTUROOT> component resolution via compilerOptions.isCustomElement.

The project uses global imports in the file app.zlib.d.ts:

//...
import LibBtn from './src/zlib/LibBtn/LibBtn.vue';
import LibIcon from './src/zlib/LibIcon/LibIcon.vue';
//...

declare module '@vue/runtime-core' {
    export interface GlobalComponents {
        //...
        LibBtn: typeof LibBtn,
        LibIcon: typeof LibIcon,
        //...
    }
}

How can I auto-import all components in ComponentName.test.js? Below is my jest.config.js:

module.exports = {
    testEnvironment: "jsdom",
    moduleFileExtensions: ["js", "json", "vue"],
    transform: {
        "^.+\\.js$": "babel-jest",
        "^.+\\.vue$": "@vue/vue3-jest",
    },
    testEnvironmentOptions: {
        customExportConditions: ["node", "node-addons"],
    },
    moduleNameMapper: {
        "^@/(.*)$": "<rootDir>/src/$1",
    },
};

Answer №1

Successfully resolved my issue with these steps

  1. Reinstalled @testing-library/jest-dom, @testing-library/user-event, @testing-library/vue.
  2. Added options in LibBtn.test.js.

import vue from "vue";
import { render, screen } from "@testing-library/vue";
import LibBtn from "./LibBtn.vue";

test('Rendering LibBtn', () => {
    const { debug } = render(LibBtn, {
        global: {
            config: {
                compilerOptions: {
                    isCustomElement: (tag) => tag.startsWith('Lib'),
                },
            },
        },
    });
    screen.debug();
});

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

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...

The validation function for email addresses in Express-validator seems to be malfunctioning

I've encountered an issue with the validation process in my code. Everything seems to be working fine except for the .isEmail method, which keeps flagging even valid email addresses as invalid. No matter how I adjust the validation rules, the problem ...

Is it sufficient to only capture 4xx errors?

Is it necessary to catch both 4xx and 5xx errors, or is catching just 4xx errors sufficient? In regular testing of my code, when would a 5xx error even occur? ...

Boxes that change and adapt to the user's input

Need guidance on a tricky problem! I am working on a form to input various cities that the user wants to visit. The form currently consists of one form box and a submit button. My goal is to allow the user to enter multiple cities by clicking an "Add 1 ...

Animate a div once the parent section becomes visible while scrolling

I previously had this function working, but it seems that I have somehow messed it up in the process. My current setup includes a scroll hijack feature that navigates users to a new section or card each time they scroll. The script adds a visible class w ...

Dependency in NPM that imports/includes from the main directory of the application

Imagine creating an application named App, which includes an npm dependency called package. The package requires that the App adheres to a specific file structure: App/ node_modules/ package/ index.js package.json folder/ file.js index.js pac ...

Why is it that comparing the childNodes of two identical nodes results in false, while comparing their innerHTML yields true?

Currently, I am in the process of developing a simple function in Node.js that compares two DOMs. My goal is to not only identify any differences between them but also pinpoint the exact variance. Interestingly, upon reconstructing identical DOMs using jsd ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

What is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Sorting dates in Vue JS can be achieved effortlessly by utilizing components and Computed Properties

I attempted to arrange the dates using computed properties but encountered issues. However, when I utilized methods and removed the slice method, the sorting worked as expected. I also tried splitting the date without success. The root cause of the problem ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

What sets apart v-model from :model-value?

I'm curious because I have trouble grasping the distinction between v-model and :model-value. According to the information in the documentation: v-model is used on a native element: <input v-model="searchText"/> However, when used on ...

Send data from JavaScript variables to PHP script

I've been trying to figure out how to pass variables from a js function to my database using php, but I've hit a roadblock. Any suggestions on how I can resolve this issue would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtm ...

What is the best way to restrict props to only accept pre-defined values?

I have a specific Use Case where I need a form to only accept the values "New" OR "Update" in a Prop called FormType. Any other values entered will trigger an error message. Currently, I am using the script setup method and I have defined props as shown b ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

Send JSON information to a Spring Boot server application

I am brand new to working with Spring Boot. Currently, I am attempting to send registration form data (in JSON format) from a Vue frontend to a Spring Boot backend. However, the backend always indicates that the received data is null. How can I properly re ...