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

新项目正常但现有项目配置Vitest时出现React refresh preamble未加载错误

解决Vitest配置到现有React项目时出现「React refresh preamble was not loaded. Something is wrong」错误

新项目中Vitest运行正常,但迁移到现有项目后触发该错误,相关信息如下:

错误详情

React refresh preamble was not loaded. Something is wrong.

相关配置与测试代码

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [ react()],
  esbuild: {
    supported: {
      'top-level-await': true
    }
  },
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/test/setupTests.js'],
    testMatch: ['./src/test/**/*.test.jsx'],
    coverage: {
      reporter: ['text', 'json', 'html'],
    }

  }
})

setupTests.js

import { expect, afterEach } from 'vitest'
import { cleanup } from '@testing-library/react'
import matchers from '@testing-library/jest-dom/matchers'

expect.extend(matchers)

afterEach(() => {
  cleanup()
})

Auth.test.js

import {fireEvent, render , screen} from '@testing-library/react'
import { describe, it } from 'vitest'
import Auth from '../components/auth/Auth'


describe('App ', () => {
  it("renders headline", () => {
    render(<Auth />)
    const btn = screen.getByTestId("sumbitButton")
    expect(btn).toBeInTheDocument()
  })


})

修复方案

这个错误是测试环境下加载了React热刷新代码导致的,现有项目大概率存在配置冲突或依赖兼容问题,可按以下步骤尝试修复:

  1. 排除测试文件的热刷新注入
    修改vite.config.js中的React插件配置,让热刷新逻辑跳过测试文件:

    plugins: [
      react({
        exclude: /\.test\.(jsx|tsx)$/ // 匹配所有测试文件,不注入热刷新代码
      })
    ],
    
  2. 仅在非测试环境加载React插件
    通过环境变量判断,测试模式下不加载热刷新相关插件:

    plugins: [
      process.env.NODE_ENV !== 'test' ? react() : null
    ].filter(Boolean),
    
  3. 同步依赖版本
    现有项目可能存在依赖版本不匹配的情况,升级相关依赖到最新稳定版:

    npm install @vitejs/plugin-react-swc@latest vitest@latest jsdom@latest --save-dev
    
  4. 检查项目自定义热刷新逻辑
    如果现有项目有手动引入ReactRefresh相关代码的自定义配置,需要确保这些逻辑在测试环境下不会被执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:43:19