You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript项目用Jest单元测试时遇模块查找错误

Vue3+TypeScript项目Jest单元测试模块找不到问题

Cannot find module '@/app/views/main/result.vue' or its corresponding type declarations.

测试文件代码

import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import { useShoppingCartStore } from "@/app/store/shopping-cart";
import Result from "@/app/views/main/result.vue"

const cartStore = useShoppingCartStore();

const wrapper = mount(Result, {
    global: {
        plugins: [createTestingPinia()],
    },
});

describe("Test", () => {
    it("is two", () => {
        // expect(something).to[matcher](value)
        console.log(cartStore.shoppingCart)
        expect(1 + 1).toBe(2);
    });
});

tsconfig配置

{
    "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "jsx": "preserve",
        "moduleResolution": "node",
        "baseUrl": ".",
        "types": ["jest", "node", "vite/client"],
        "paths": {
            "@/*": ["./src/*"],
            "@shared/*": ["./src/shared/*"],
            "@controls/*": ["./src/app/components/controls/*"]
        },
        "outDir": "./dist",
        "strict": true,
        "importHelpers": true,
        "experimentalDecorators": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "sourceMap": true,
        "noImplicitAny": false,
        "lib": ["esnext", "dom", "dom.iterable", "scripthost"],
        "emitDecoratorMetadata": true
    },
    "include": ["src/app/**/*.ts", "src/app/**/*.vue"],
    "exclude": ["src/server/**/*", "node_modules", "dist"]
}

jestconfig配置

module.exports = {
    preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
    transform: {
        "^.+\\.vue$": "@vue/vue3-jest",
        "^.+\\.(t|j)s$": "ts-jest",
    },
    "moduleDirectories": ["src", "node_modules"],
    "moduleFileExtensions": ["js", "json", "ts"],
    "testMatch": ["**/__tests__/*.{j,t}s?(x)", "**/tests/unit/**/*.spec.{j,t}s?(x)", "**/*.spec.{j,t}s?(x)"],
    "rootDir": "src",
    "collectCoverageFrom": ["**/*.(t|j)s"],
    "coverageDirectory": "../coverage",
    //testEnvironment should be jsdom for frontend, could cause issues with server tests
    "testEnvironment": "jsdom",
    "moduleNameMapper": {
        "@shared/(.*)": "<rootDir>/shared/$1",
        "@server/(.*)": "<rootDir>/server/$1",
        "@/(.*)": "<rootDir>/($1)",
        "@controls/(.*)": "<rootDir>/app/components/controls/$1",
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/tests/mockUtils/fileImport.js",
        "\\.(css|less)$": "<rootDir>/tests/mockUtils/styleImport.js",
    },
    globals: {
        "ts-jest": {
            tsConfig: "tsconfig.server.json",
        },
    },
};

解决步骤

1. 修复Jest路径映射错误

jest配置中@/(.*)的映射写法有误,多余的括号会导致路径解析失败,修改为:

"@/(.*)": "<rootDir>/$1",

2. 修正ts-jest的tsconfig指向

当前jest指定了tsConfig: "tsconfig.server.json",但项目主配置是tsconfig.json,且jest的rootDir为src,需要回退一级指向根目录的配置文件:

globals: {
    "ts-jest": {
        tsConfig: "../tsconfig.json",
    },
},

3. 添加.vue文件类型声明

在src目录下创建shims-vue.d.ts,写入:

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

并将该文件加入tsconfig的include数组:

"include": ["src/app/**/*.ts", "src/app/**/*.vue", "src/shims-vue.d.ts"]

4. 让Jest识别.vue文件

在jest配置的moduleFileExtensions中添加vue:

"moduleFileExtensions": ["js", "json", "ts", "vue"],

5. 验证文件路径和拼写

确认@/app/views/main/result.vue对应的实际路径src/app/views/main/result.vue存在,且文件名、路径拼写完全匹配(注意大小写敏感)。

内容的提问来源于stack exchange,提问作者niklasbec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:05:21