Encountering a "Module not found" error in Vue3 Jest when utilizing a

Currently, I am utilizing Vue3 alongside TypeScript and attempting to create unit tests using Jest. Following the documentation, I have defined a module in the shims-vue.d.ts file as shown below:

/* eslint-disable */

declare module '*.vue' {
    import type { DefineComponent } from 'vue'
    const component: DefineComponent<{}, {}, any>
    export default component
}

import { Store } from '@/store/index'

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $store: Store
    }
}

This setup allows me to successfully utilize $store within components. However, once I added this module to shims-vue.d.ts, I encountered an issue where I could no longer import my components in test files. Here's an example of my test file:

import { mount } from '@vue/test-utils'
import Increment from '@/components/Increment.vue'

import { createStore } from 'vuex'

const store = createStore({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state: any) {
            state.count += 1
        }
    }
})

describe('Increment.vue', () => {
    test('something', async () => {
        const wrapper = mount(Increment, {
            global: {
                plugins: [store]
            }
        })

        await wrapper.get('[data-test="increment"]').trigger('click')

        expect(wrapper.get('[data-test="count"]').text()).toBe(1)
    })
})

An error that I'm encountering states:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):        tests/unit/components/increment.spec.ts:2:23 - error TS2307: Cannot find module '@/components/Increment.vue' or its corresponding type declarations.
. Despite verifying that the path and names are correct, I'm still facing this issue. Any assistance on resolving this problem would be greatly appreciated. Thank you.

Below is the code for Increment.vue:

<template>
    <div>
        <div data-test="count">
            {{ count }}
        </div>
        <button data-test="increment" @click="increment()">
            Increment
        </button>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { mapState } from 'vuex'

export default defineComponent({
    computed: {
        ...mapState([
            'count'
        ])
    },
    methods: {
        increment() {
            this.$store.commit('increment')
        }
    }
})
</script>

<style scoped>
    
</style>

Answer №1

The issue was identified and resolved successfully. Initially, I attempted to utilize $store and defined the module in the shims-vue.d.ts file. However, it was necessary to create that module in a separate file named vuex.d.ts. Once this adjustment was made, the problem was rectified.

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

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

v-treeview component triggering method execution twice upon input

I'm facing an issue with my Vue component that contains a treeview. Upon selecting a node, the goal is to update an array and display the checkbox as selected. However, I'm encountering a problem where if I select elements from one folder in the ...

Tips for formatting a phone number using regular expressions in [Vue 2]

I am currently working on creating regex code that will meet the following requirements: Only allow the first character (0th index) in a string to be either a '+' symbol or a number (0-9). No non-numerical values (0-9) should be allowed anywhere ...

The function type is not as strict as the return type in terms of enforcement

I am working on defining a function type that enforces the return type (Object) to have the exact object properties specified in the return type definition. Despite my efforts, the compiler is not enforcing strict adherence to the returned object properti ...

What's the best way to retrieve the quantity of each item through v-for in Vue?

In my Vue code snippet below: var itembox = new Vue({ el: '#itembox', data: { items: { cookiesncreme: { name: "Cookies N Cream", description: "description" }, ch ...

Issue with displaying a div based on $route path change in certain conditions not being resolved

I am a newcomer to Vue and I have a requirement to conditionally display an element based on the router link. The idea is to show the element when the link is '/', or home, and hide it when moving to any other link. I initially attempted to use a ...

The route does not support the GET method, please use the POST method instead

I am currently in the process of developing a commenting system. As I attempt to post a new comment, though, I encounter an error when trying to send it at . Unfortunately, the GET method is not supported for this route. Only POST methods are allowed. ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

The issue with Framer Motion's scrollYProgress not updating

Currently, I am working on a project that involves Framer Motion and Next.js. In my implementation, I am utilizing the Framer motion useScroll hook to keep track of the user's scroll activity on the page. However, it seems like the scroll tracking fun ...

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

What is the process of exporting a module assigned to a variable in JavaScript?

My approach to making the require visible in <app></app> is as follows: index.html: <script> var electron = require('electron') </script> <app></app> <script src="bundle.js"></script> App.vue: ...

Managing multiple `ng-content` slots in Angular can be a daunting task. Here

I am facing an issue with a component where I have declared an input as follows: @Input() isOverlay: boolean The template html for this component looks like this: <ng-template *ngIf="isOverlay" cdkConnectedOverlay [cdkConnected ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...

Having trouble with the search bar in my Vue Flickr application - the results are not as expected

I am currently working on a Vue project to build a Flickr app and I would like to implement a search bar for users to find photos based on specific tags. Although I have made some progress, I have noticed that the photos retrieved do not always contain th ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

There are no records in the Vue.js component's list

I am struggling to fetch data from a table using relations. The goal is to retrieve products with an ID from the products table, utilizing product_id as the foreign key from the selectedproducts table. However, upon inspecting my network console, the list ...

`How can I make Vue listen for events?`

After making corrections to fix an unreported syntax error (check comments), the code now functions as intended. I am facing an issue with my event handler not triggering in the Vue code below. There are two components, named posts and post, along with a ...

Only elements that are considered valid can be wrapped by ReactWrapper, such as those from material-ui or

I am currently working on testing a component's function, but I keep encountering an issue with ShallowWrapper wrapping valid elements. Here is the structure of the component file - TextInput.js: /* eslint-disable react/require-default-props */ imp ...

Utilize the reducer from another slice in Redux Toolkit

I am working with an authSlice const authSlice = createSlice({ name: 'authStore', initialState, reducers: { logout(state = initialState) { return { ...state, isAuthenticated: false }; }, }, extraReducers: (builder) => { ...

Utilizing Angular for Webcam Integration

After trying out this code snippet: <video autoplay playsinline style="width: 100vw; height: 100vh;"></video> <script> navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then(stream =&g ...