我试图在Svelte
应用程序(具有Typescript
支持)上设置vitest
的一些单元测试,并且我得到以下错误:
ParseError: D:/(...)/src/Overlay.svelte:23:17 Unexpected token
在这个文件中,对应于:
<!-- Overlay.svelte -->
<script lang="ts"> // line 1
// (...)
let startDate:string = tomorrows_date(); // line 23
// ^--23:17
我已经尝试从GitHub上的官方Vitest示例中复制结构。
我到处看了一下,并试图使用vitest-svelte-kit
或添加svelte.config.js
(由于import
语句"在模块之外"而不起作用)
在我的配置下面找到。
在我的package.json
中我添加了所有这些:
// package.json
(...)
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --no-clear -c",
"validate": "svelte-check",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "vitest",
"test:ui": "vitest --ui",
"coverage": "vitest run --coverage"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-typescript": "^8.0.0",
(...)
"@sveltejs/vite-plugin-svelte": "^1.0.0-next.45",
"@testing-library/svelte": "^3.1.3",
"@tsconfig/svelte": "^2.0.0",
"@vitest/ui": "latest",
"jsdom": "latest",
"rollup": "^2.67.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.5",
"rollup-plugin-svelte": "^7.1.0",
"rollup-plugin-terser": "^7.0.2",
"svelte": "^3.49.0",
"svelte-check": "^2.0.0",
"svelte-preprocess": "^4.0.0",
"tslib": "^2.0.0",
"typescript": "^4.0.0",
"vitest": "^0.18.1",
"vitest-svelte-kit": "^0.0.6"
},
"dependencies": {
"sirv-cli": "^2.0.2",
"svelte-material-ui": "^6.0.0-beta.16"
},
"stackblitz": {
"startCommand": "npm run test:ui"
}
}
// tsconfig.json
{
"extends": "@tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
}
// vitest.config.js
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [
svelte({ hot: !process.env.VITEST }),
],
test: {
globals: true,
environment: 'jsdom',
},
})
我没有svelte.config.js
TS需要svelte-preprocess
,测试配置可能不会隐式加载它。您可以将其传递给插件或通过svelte.config.js
:
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess({ ... })
};
在您的测试配置文件中使用以下配置:
import { defineConfig } from 'vitest/config'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import sveltePreprocess from 'svelte-preprocess'
export default defineConfig({
plugins: [
svelte({
hot: !process.env.VITEST,
preprocess: [sveltePreprocess({ typescript: true })] // <-- this line allow vitest to parse svelte component using typescript
})
],
test: {
include: ['imports/**/*.vitest.{js,ts}'],
globals: true,
environment: 'jsdom',
},
})