Tips for preventing the [Vue warn] message in custom directive implementation

I've encountered an issue with a custom directive that I created. Despite it functioning properly, when running the mocha test for the component utilizing this directive, I received a warning message stating

[Vue warn]: Failed to resolve directive: scroll-text
. Can someone provide guidance on how to rectify this problem?

test file:

import { shallowMount } from "@vue/test-utils"
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"

Vue.use(scrollText)

const stubs = [
    "z-text-field",
    "v-progress-circular",
    "v-icon",
    "z-btn"
]

describe("ZSourcesList.vue", () => {
    const sources = []
    for (let i = 0; i < 20; i++) {
        sources.push({
            field: "source",
            // format numbers to get 2 diggit number with leading zero 1 -> 01
            value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
            __typename: "SuggestV2Result"
        })
    }

    it("displays 'No matching sources found' if there are no sources", () => {
        const wrapper = shallowMount(ZSourcesList, {
            mocks: {
                $apollo: {
                    queries: {
                        suggestions: {
                            loading: false,
                        },
                    },
                },
            },
            stubs,
            sync: false,
            data() {
                return {
                    suggestions: [],
                }
            },
        })

        expect(wrapper.find(".notification .z-note")).to.exist
    })
})

Answer №1

One way to improve your custom directive is by registering it on a local vue instance and then mounting it to that specific vue instance.

import { shallowMount, createLocalVue } from "@vue/test-utils" 
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"

const localVue = createLocalVue()
localVue.use(scrollText) // Make sure to register the plugin on the local vue instance

const stubs = [
    "z-text-field",
    "v-progress-circular",
    "v-icon",
    "z-btn"
]

describe("ZSourcesList.vue", () => {
    const sources = []
    for (let i = 0; i < 20; i++) {
        sources.push({
            field: "source",
            value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
            __typename: "SuggestV2Result"
        })
    }

    it("displays 'No matching sources found' if there are no sources", () => {
        const wrapper = shallowMount(ZSourcesList, {
            mocks: {
                $apollo: {
                    queries: {
                        suggestions: {
                            loading: false,
                        },
                    },
                },
            },
            localVue, // Mount this component on the localVue
            stubs,
            sync: false,
            data() {
                return {
                    suggestions: [],
                }
            },
        })

        expect(wrapper.find(".notification .z-note")).to.exist
    })
})

By utilizing a local vue instance in test cases, you can avoid polluting the global vue instance and minimize potential side effects in other tests.

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

Is there a way for me to access the property value utilized in the Cypress test?

I am currently working on a Cypress example that can be found at the following link: : cy.get('[data-test-id="test-example"]') .invoke('css', 'position') .should('equal', 'static') Despite my ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Is it possible to incorporate click methods within vuex?

Recently, I've been delving into learning Vue and Vuex. One thing I noticed is that I have repetitive code in different components. To streamline this, I decided to utilize Vuex to store my data in index.js, which has proven to be quite beneficial. No ...

Problem with Clerk's authentication() functionality

Currently facing an issue with the Clerk auth() helper (auth() documentation) while working with react and next 13 (app router). When trying to access both userId and user from auth(), const { userId, user } = auth();, it seems that userId contains a val ...

Scope binding is successful, but accessing the array is only possible after adding an Alert() function

Within my Angular controller, I'm utilizing the SharePoint JavaScript Object Model to fetch data from the Taxonomy (term store). Due to SharePoint's JSOM not being a conventional Angular function that can be easily understood by the scope, I util ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

The script in Vue.js Build.js keeps running indefinitely

'use strict' require('./check-versions')() process.env.NODE_ENV = 'production' const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('ch ...

What is the best way to trigger a data update in the parent component when the child component in a Vue component is clicked?

Here is the structure of my first component (child component) : <template> ... </template> <script> export default { ... methods: { addPhoto() { const data = { id_product: this.idProduc ...

Asynchronous Node operations with Promise.all

When working on a basic JS program, I encountered the need for asyncOperation2 and asyncOperation3 to run in sequence with asyncOperation1. The specific order of execution required is either 1,2,3 or 2,3,1. Additionally, after completing these operations, ...

What are the best practices for managing user forms and uploading files?

How should data in text fields and file upload fields be handled according to best practices? This question is a more generalized version of one I previously asked, which can be found here. Let's consider the scenario of a user registering an accoun ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

The JQUERY Click event fails to trigger only on the initial click

While attempting to display the name stored as a data value for each button in the code, I encountered an issue where it wouldn't work on the first click event call. However, after the initial click, it operated normally. It is important to note that ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

What is the most efficient method for managing window properties and child components in React/Redux?

My <Layout> component loads different child components based on the page. Some of these children may have tabs, while others may not. This variation in content affects how scrolling should work and consequently influences the structure of the scroll ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

Trouble with React routes: only fixed after refreshing the page

import React, { useEffect, useState } from 'react'; import { Container, AppBar, Typography, Grow, Grid, useTheme } from '@material-ui/core'; import { useDispatch } from 'react-redux'; import { BrowserRouter, Router, Route, Swi ...

Steps to transfer an array from an HTML page to Node.js and subsequently save it in a database

Looking for guidance on how to transfer a JavaScript array using Node.js to MySql. Seeking helpful videos or explanations to clarify the process. Thank you! ...

Attempting to send an AJAX request to a different server (not functioning with the provided example)

UPDATE - Issue Resolved. Many thanks to everyone who provided input. After conducting extensive research, I discovered that instead of CORS, I needed to focus on JSONP all along. I have read several tutorials and believe I now have a good grasp of the con ...

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

Saving an edited polygon path in Vue using Google Maps

In my Vue component named BaseMap, there is a nested component called Location. The Location component features an editable Polygon marker. // BaseMap <GmapMap> <Location :location="location" /> </GmapMap> // Location <gmap-marker ...