如何为Vuetify3(Vue3+TypeScript)配置Jest测试?
Vuetify3 + Vue3 + TypeScript 集成Jest测试报错问题
团队要求必须使用Jest而非Vitest,当前技术栈为Vuetify3(Vue3)+TypeScript。Vue2与Jest的配置文档随处可见,但Vue3相关的配置资源非常匮乏,Vuetify官方仅提供了Vitest的测试教程。
我们尝试了多种配置方式,但在测试包含Vuetify组件的文件时,始终出现以下错误(测试纯HTML元素的文件无此问题):
SyntaxError: Cannot use import statement outside a module 2 | import { describe, expect } from '@jest/globals'; 3 | import { mount } from "@vue/test-utils" > 4 | import { createVuetify } from "vuetify"
测试文件示例(测试包含Vuetify v-dialog和v-btn的组件)
import { describe, expect } from '@jest/globals'; import { mount } from "@vue/test-utils" import { createVuetify } from "vuetify" import * as components from "vuetify/components" import * as directives from "vuetify/directives" import MyComponent from "./MyComponent.vue" describe("MyComponent.vue", () => { it('renders correctly', () => { const vuetify = createVuetify({ components, directives }) const wrapper = mount(MyComponent, { global: { plugins: [ vuetify ] } }) expect(wrapper.find(`[data-testid="myTestId"]`).exists()).toBe(true) }) })
jest.config.js 配置
export default { preset: 'ts-jest', testEnvironment: 'jsdom', transform: { "^.+\\.vue$": '@vue/vue3-jest', "^.+\\.js$": "babel-jest", "^.+\\.ts$": "ts-jest", }, testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)$', moduleFileExtensions: ['vue', 'js', 'ts'], moduleNameMapper: { "\\.(css|less|scss)$": "<rootDir>/testHelper/__mocks__/styleMock.ts", "^@/(.*)$": "<rootDir>/src/$1", }, testEnvironmentOptions: { customExportConditions: ["node", "node-addons"], }, transformIgnorePatterns: [ '<rootDir>/node_modules/(?!vuetify)' ], }
babel.config.json 配置
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript" ] }
package.json 片段
{ "type": "module", ... "dependencies": { "@babel/core": "^7.23.5", "@babel/preset-env": "^7.23.5", "@babel/preset-typescript": "^7.23.3", "@babel/types": "^7.21.4", "@jest/globals": "^29.7.0", "@testing-library/jest-dom": "^6.1.4", "@types/babel__core": "^7", "@types/babel__preset-env": "^7", "@types/eslint": "^8", "@types/jest": "^29.5.10", "@types/node": "^18.15.0", "@vitejs/plugin-vue": "^4.0.0", "@vue/eslint-config-typescript": "^11.0.0", "@vue/test-utils": "^2.4.3", "@vue/vue3-jest": "^29.2.6", "babel-jest": "^29.7.0", "core-js": "^3.29.0", "eslint": "^8.54.0", "eslint-plugin-vue": "^9.18.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "jest-transform-stub": "^2.0.0", "ts-jest": "^29.1.1", "ts-node": "^10.9.1", "typescript": "^5.0.0", "vite": "^4.2.0", "vite-plugin-vuetify": "^1.0.0", "vue": "^3.3.9", "vue-router": "^4.0.0", "vue-tsc": "^1.2.0", "vuetify": "^3.4.4" } }
恳请各位提供解决方案,如需更多细节可随时告知。
内容的提问来源于stack exchange,提问作者Mina
相关产品推荐
相关产品推荐

