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

Vite+Vitest+Svelte项目引入@vaadin/notification测试报错求助

解决方案

方案1:修正CommonJS插件并配置依赖转译

你的vitest.config.ts中commmonjs存在拼写错误(多了一个m),先修正该问题,再配置Vitest对@polymer/polymer进行转译,解决CommonJS与ES模块的解析冲突:

import { defineConfig } from 'vitest/config'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import commonjs from '@rollup/plugin-commonjs'

export default defineConfig({
  plugins: [svelte(), commonjs()],
  test: {
    globals: true,
    deps: {
      inline: ['@polymer/polymer']
    }
  }
})

方案2:Mock无关依赖

由于测试仅针对sum纯函数,无需加载@vaadin/notification组件,可直接在测试文件中mock该模块,跳过实际依赖加载:

import { describe, test, expect } from 'vitest' 
import { sum } from './util'

// Mock @vaadin/notification,避免加载实际模块引发解析错误
vi.mock('@vaadin/notification', () => ({}))

test('123', () => {
    expect(sum(1, 1)).toBe(2)
})

方案3:预构建CommonJS依赖

通过Vite的optimizeDeps配置预构建@polymer/polymer,将其转为ES模块格式,让Vitest可以正确解析:

import { defineConfig } from 'vitest/config'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import commonjs from '@rollup/plugin-commonjs'

export default defineConfig({
  plugins: [svelte(), commonjs()],
  optimizeDeps: {
    include: ['@polymer/polymer']
  },
  test: {
    globals: true,
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:07:35