Encountering error 2307 "Cannot find module" when using Vue 3 with script setup and TypeScript

I am currently attempting to run unit tests in my Vue3 project using vue/test-utils and jest.

Upon running the npm run test script, the test fails due to an error with the import:

error TS2307: Cannot find module 'pathtofile/file.vue'

I have tried adding a shims-vue.d.ts file in my src folder with

define module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<Record<string,unknown>, Record<string,unknown>, unknown>
  export default component
}

The project is built with Vitejs. Here's the tsconfig:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "react": ["./stub/types__react"]
    },
    "skipLibCheck": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue"
  ],
  "exclude": [
    "node_modules",
    "node_modules/@vueuse/core/node_modules/@vueuse/shared/index.d.ts"
  ]
}

and the jest.congif.js:

module.exports = {
  testEnvironment: 'jsdom',
  collectCoverage: true,
  collectCoverageFrom: ['src/**/*.{[tj]s?(x),vue}'],
  coverageDirectory: 'tmp/coverage',
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '/src/main.ts',
    '/src/assets/*',
    '/src/components/*',
    '/src/connector/*',
    '/src/enums/*',
    '/src/graphql/*',
    '/src/libs/*',
    '/src/router/*',
    '/src/store/*',
    '/src/types/*',
    '/src/utils/*',
    '/src/views/*'
  ],
  coverageReporters: ['html', 'text', 'lcov'],
  coverageThreshold: {
    global: {
      branches: 50,
      functions: 50,
      lines: 50,
      statements: 50
    }
  },

  moduleFileExtensions: ['js', 'ts', 'json', 'vue'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  transform: {
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.vue$': '@vue/vue3-jest'
  }
};

The specific tests that are failing:

import { config, mount } from '@vue/test-utils';
import { createI18n, I18n, I18nOptions } from 'vue-i18n';
import { createPinia, setActivePinia } from 'pinia';
import { createTestingPinia } from '@pinia/testing';
import ElementPlus from 'element-plus';
import dayjs from 'dayjs';

import MaterialIcon from '@/components/common/material-icon/material-icon.vue'; <--- error
import QuickFilter from '@/components/common/quick-filter/quick-filter.vue'; <--- error

import localizedFormat from 'dayjs/plugin/localizedFormat';
import timezone from 'dayjs/plugin/timezone';
import duration from 'dayjs/plugin/duration';
import advancedFormat from 'dayjs/plugin/advancedFormat';

dayjs.extend(localizedFormat);
dayjs.extend(timezone);
dayjs.extend(advancedFormat);
dayjs.extend(duration);

beforeEach(() => {
  // creates a fresh pinia and make it active so it's automatically picked
  // up by any useStore() call without having to pass it to it:
  // `useStore(pinia)`
  setActivePinia(createPinia());
});

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  globalInjection: true,
  messages: {
    en: {
      dates: {
        'yesterday': 'Yesterday',
        '7days': '7 Days',
        '30days': '30 Days'
      }
    }
  }
} as I18nOptions) as I18n;

config.global.mocks = {
  dayjs
};
config.global.components = {
  'MaterialIcon': MaterialIcon
};
config.global.plugins = [i18n, createTestingPinia(), ElementPlus];

describe('Quick filter', () => {
  it('renders the filters', () => {
    const wrapper = mount(QuickFilter);
    const filters = wrapper.findAll('.quick-filter__item');

    expect(filters.length).toBe(3);
  });
});

I am unsure why this error is happening.

Could this be related to Vue script setup? Or is it something else?

Answer №1

One possible solution is to include "**/*.d.ts" in the tsconfig.json file under the "include" Array.

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

Implementing multi-authentication in Laravel 8 with RolesMiddleware

I am currently in the process of building a Laravel 8 project that involves multiple authentication based on user roles. As a newcomer to Laravel, I initially created separate Middleware for each role (isAdminMiddleware, isUserMiddleware, isManagerMiddlewa ...

Is it Possible for the Number Array Type to Not Be Recognized as an Array?

export class ... { single: any[] = []; multi: any[] = []; view: number[] = [700, 400]; ... <Removed for brevity> } Error Message: It says 'Type 'number[]' is not assignable to t ...

Interacting with Vue3 List Items by Manipulating the HTML DOM

I am currently using Vue 3 and I have a requirement to manipulate a specific list item when a button is clicked. Below is the HTML code snippet: <socialDiv v-for="(follower, i) in followerList" :key="follower.id" :ref="el => ...

Finding the precise Time zone with date-fns: A comprehensive guide

I've implemented a date pipe using the date-fns library for formatting dates. Here is the code: date.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { format } from 'date-fns'; @Pipe({ name: 'formatDate ...

Utilize Property Binding to Access the Map

I am struggling to extract a value from a Map and use it as the background color of a div element, but I can't seem to get it right. My syntax seems off. What mistake am I making? <div [style.background-color]="bgcolor" width="50px" height="50px"& ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Unable to retrieve the data property from the Axios response object following a successful GET request: The property 'data' is not present in the type 'void'

Currently, I am working on a personal project using React and TypeScript to enhance my skills. However, I have encountered a puzzling error in the following code snippet, which involves using Axios to fetch data: const fetchItem = async () => { const ...

Is it possible to have a synchronous function imported in typescript?

// addons.ts export interface addon { name: string; desc: string; run: (someparam: any) => void; } export function loadaddons(): Array<addon> { let addons: Array<addon> = []; fs.readdirSync(path.join(__dirname, "addons")) .fi ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...

Issue: Angular ERROR TypeError - Cannot access the property 'push' of a null value

In my code, I have a property called category = <CategoryModel>{};. The CategoryModel model looks like this: export class CategoryModel { public name: string; public description: string; public image: string; public products?: ProductModel[]; ...

What is the best method for distributing an Angular service from a library created using ng generate library?

I'm currently facing a challenge in sharing a service from the npm package that I created using ng g library with my Angular hosting application. While I have experience in linking components and directives, I'm a bit lost when it comes to servic ...

Adjusting various angular-cli configuration files or providing input variables

My application caters to different customers, requiring personalized configurations based on their needs. I am looking for a way to customize the settings in the angular-cli.json file each time I run ng build. Is there a method to: 1) Dynamically cha ...

Is it truly possible to return a reactive variable that updates its value asynchronously?

While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asyn ...

An error occurred while attempting to access the 'transformFile' property of an undefined object within the Vue-Native framework

I've been keen to experiment with vue-native, but I keep encountering the following error message: bundling failed: TypeError: Cannot read property 'transformFile' of undefined Behold my package.json file: { "name": "vueNativeDeneme", ...

Changing {number, Observable<string>} to Observable<number, string> is a necessary transformation to be made

Is there a way to convert an array of objects with the following structure: { id: number, data: Observable<string> } into an array of objects with this structure: Observable<{id: number, data: string}> using only RxJS operators? ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Retrieve component information from the service

Incorporated within my component is a form that I'm utilizing with reactive form and my intention is to reach this form through my service. For example: const id = MyComponent.id and inside my component: @Output: public id: number = 7; ...

I encountered an error when attempting to utilize a recursive type alias in a generic context

When attempting to use a recursive type alias in a generic function, TypeScript v3.7.5 throws the error message: Type instantiation is excessively deep and possibly infinite.(2589). type State = { head: { title: string; description: s ...

Utilizing webpack for code splitting, integrating it with Vue and dynamically loading CSS files

Implementing code-splitting suggestions from Webpack and vue-router, I have opted to lazy load bulky pages in my routes using dynamic import like so: const Login = () => import("../views/Login/Login.vue"); However, when the login.vue page contains an ...

Maximizing the reusability of sub-components in a VueJS parent component: Importing sub

If I have an App.vue file structured like this: <template> <task-list> <task>Task 1</task> <task>Task 2</task> </task-list> </template> <script> import TaskList from './tas ...