求解vue-jest不生效,解析不了<template>标签?

新手上路,请多包涵

我的vue版本是2.6+,使用过程vue-jest没有生效,报错如下:
image.png

/Volumes/data/develop/code/web/xx/xxx-service-tree/src/framework-service-tree/components/HelloWorld.vue:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<template>                                                                             
 SyntaxError: Unexpected token '<'
      1 | import { shallowMount } from '@vue/test-utils';
    > 2 | import HelloWorld from '../src/framework-service-tree/components/HelloWorld.vue';
        | ^
      3 |
      4 | // describe('EntitySwitch.vue', () => {
      5 | //     // let wrapper;

引入的文件是src目录下,并不是node_modules中的,网上搜索报错都是node_modules下的,这个问题要如何解决
jest.config.js配置如下

module.exports = {
    preset: 'ts-jest/presets/js-with-babel',
    testEnvironment: 'jsdom',
    transformIgnorePatterns: ['node_modules/(?!(sucrase)/)'],
    moduleFileExtensions: ['js', 'ts', 'json', 'vue'],
    transform: {
        '^.+\\.vue$': 'vue-jest', // Vue 2 专用转换器
        '^.+\\.tsx?$': 'ts-jest',
        '^.+\\.js$': 'babel-jest',
    },
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy', // CSS 模拟处理
    },
    testMatch: ['**/tests/**/*.spec.[jt]s?(x)'],
    setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'],

    // 添加 Vue 2 模板编译器路径
    globals: {
        'vue-jest': {
            templateCompiler: {
                compiler: require('vue-template-compiler'),
            },
        },
    },
    testEnvironmentOptions: {
        customExportConditions: ["node", "node-addons"]
    }
};

.babelrc配置如下

{
    "presets": [
      "@babel/preset-env",
      "@babel/preset-typescript"
    ],
    "plugins": [
      ["@babel/plugin-transform-modules-commonjs"] // Vue 2 需要此插件
    ]
}

package.json增加依赖如下

"@babel/core": "^7.26.10",
"@babel/preset-env": "^7.26.9",
"@babel/preset-typescript": "^7.26.0",
"@types/jest": "^29.5.14",
"@types/jsdom": "^21.1.7",
"@vue/test-utils": "^1.3.6",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"jsdom": "^26.0.0",
"ts-jest": "^29.2.6",
"vue-jest": "^4.0.1",

vue文件如何才能正确添加单测

阅读 739
avatarAI BotBETA

根据你的配置和报错信息,问题可能出在缺少 vue-template-compiler 依赖或配置未正确关联。以下是解决方案:

1. 安装必要依赖

npm install vue-template-compiler@2.6.14 --save-dev
# 确保与你的 vue 版本严格一致

2. 修正 Jest 配置(jest.config.js)

transform: {
-    '^.+\\.vue$': 'vue-jest',
+    '^.+\\.vue$': '@vue/vue2-jest', // 明确使用 Vue2 专用包
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
},
globals: {
-    'vue-jest': {
-        templateCompiler: {
-            compiler: require('vue-template-compiler'),
-        },
-    },
+    // Vue2 无需额外配置 compiler
},

3. 验证 Babel 配置
确保 .babelrc 包含对 Vue JSX 的支持:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript"
  ],
  "plugins": [
+   "transform-vue-jsx",
    ["@babel/plugin-transform-modules-commonjs"]
  ]
}

4. 检查依赖版本兼容性
建议升级相关依赖版本:

{
  "dependencies": {
    "vue": "^2.6.14",
    "vue-template-compiler": "^2.6.14",
    "@vue/test-utils": "^1.3.0",
    "vue-jest": "^3.0.7" // Vue2 推荐使用 3.x 版本
  }
}

5. 创建 TypeScript 声明文件(如存在类型错误)
在项目根目录创建 shims-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

常见问题排查点:

  1. 确保 vuevue-template-compiler 版本完全一致
  2. 检查测试文件是否位于 tests 目录(根据你的 testMatch 配置)
  3. 清理 Jest 缓存:

    npx jest --clearCache

完整可运行的测试示例:

import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })
})
2 个回答
新手上路,请多包涵

mark mark mark 有没有了解的

  1. 首先,确保你的 vue-jest 版本与 Vue 2.6+ 兼容。对于 Vue 2.x,你应该使用 vue-jest v3.x 而不是 v4.x(v4.x 是为 Vue 3 设计的):
npm uninstall vue-jest
npm install --save-dev vue-jest@3.0.7
  1. 修改你的 Jest 配置 (jest.config.js):
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'ts', 'tsx'],
    transform: {
        '^.+\\.vue$': 'vue-jest',
        '^.+\\.(ts|tsx)$': 'ts-jest',
        '^.+\\.(js|jsx)$': 'babel-jest'
    },
    transformIgnorePatterns: [
        '/node_modules/(?!vue-router)'
    ],
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy'
    },
    testMatch: ['**/tests/**/*.spec.(js|jsx|ts|tsx)'],
    
    // Vue 2 特定配置
    globals: {
        'vue-jest': {
            babelConfig: {
                presets: ['@babel/preset-env']
            }
        },
        'ts-jest': {
            tsconfig: 'tsconfig.json'
        }
    }
};
  1. 确保你的 .babelrcbabel.config.js 配置适用于 Vue 2:
{
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "node": "current"
            }
        }],
        "@babel/preset-typescript"
    ],
    "plugins": [
        "@babel/plugin-transform-modules-commonjs"
    ]
}
  1. 创建一个基本的测试文件示例 (HelloWorld.spec.js 或 HelloWorld.spec.ts):
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/framework-service-tree/components/HelloWorld.vue';

describe('HelloWorld.vue', () => {
    it('renders correctly', () => {
        const wrapper = shallowMount(HelloWorld, {
            propsData: {
                msg: 'Hello Jest'
            }
        });
        expect(wrapper.text()).toMatch('Hello Jest');
    });
});
  1. 确保 package.json 中有正确的测试脚本:
"scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
}

如果上述步骤仍然不起作用,可能需要检查以下几点:

  1. 确保安装的依赖版本兼容:

    "devDependencies": {
        "@babel/core": "^7.12.0",
        "@babel/preset-env": "^7.12.0",
        "@babel/preset-typescript": "^7.12.0",
        "@vue/test-utils": "^1.0.0",
        "babel-core": "^7.0.0-bridge.0",
        "babel-jest": "^26.0.0",
        "jest": "^26.0.0",
        "ts-jest": "^26.0.0",
        "vue-jest": "^3.0.7",
        "vue-template-compiler": "^2.6.0" // 必须与你的 Vue 版本匹配
    }
  2. 添加一个 jest.setup.js 文件处理全局 Vue 配置
  3. 确保 vue-template-compiler 版本与你的 Vue 版本完全匹配
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题