Vitest Error : React refresh preamble was not loaded. Something is wrong
Asked Answered
F

7

7

I am new to testing and I was trying to use vitest for testing my mern social media app. looking for references to test a react component using vitest i found this article https://eternaldev.com/blog/testing-a-react-application-with-vitest. following this when i try to render a component i get the error React refresh preamble was not loaded. Something is wrong on running tests . below are relevant codes :

register.test.tsx

import { expect, test, describe } from 'vitest';
import { render, screen } from '@testing-library/react';
// import Register from '../../components/Authentication/Register';
import Fake from '../../Fake';

describe('Registration Component Full functionality testing', () => {

    test("should be showing Signup heading", () => {

        render(<Fake />);
        expect(screen.getByText(/Fake/i)).toBeDefined()
    })
})

Fake.tsx

import React from 'react'

const Fake: React.FC = () => {
    return (
        <div>Fake</div>
    )
}

export default Fake

vite.config.ts

/// <reference types="vitest" />
/// <reference types="vite/client" />

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './setupTest.ts'
  }
})

I am open to share more information about my codebase if required . thanks.

I was trying to render a react component in a test coded using vitest but was getting the error React refresh preamble was not loaded. Something is wrong on doing so. I am expecting any one who knows the answer to deliver a structured answer along with the explanation for what was missing or what was wrong .

Forklift answered 7/8, 2023 at 18:6 Comment(0)
F
11

I have the same problem and I have tried both methods above but it doesn't work.

I found this discussion to help find a solution, Running browser mode errors "@vitejs/plugin-react can't detect preamble"

after I checked version 3 @vitejs/plugin-react, it turned out to have this bug.

the solution is quite easy

from :

"@vitejs/plugin-react": "3.0.1"

change to version 4+:

"@vitejs/plugin-react": "4.2.1"
Foehn answered 20/12, 2023 at 4:9 Comment(3)
Yep, I read all the articles and issue reports and everything. This is the thing that fixed it. THANK YOU!Maggie
had a similar issue with @vitejs/plugin-react-swc, updating it has helpedRepository
Worked for me as well. This should be marked as the solution. I read the documentation and they explained that v4.2.1 fixed this issue.Sterilization
W
11

If you are using Laravel.

Simply add

@viteReactRefresh

into the HTML head in your Laravel blade file(app.blade.php/welcome.blade.php)

 <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Laravel</title>
            @viteReactRefresh 
            @vite(['resources/css/app.css', 'resources/js/Website/app.jsx'])
            @inertiaHead
        </head>
        <body>
            @inertia
        </body>
    </html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        @viteReactRefresh 
        @vite(['resources/css/app.css', 'resources/js/Website/app.jsx'])
        @inertiaHead
    </head>
    <body>
        @inertia
    </body>
</html>

Please ensure you're using updated version of plugin-react "@vitejs/plugin-react": "^4.2.1"

Wert answered 4/4, 2024 at 9:32 Comment(1)
adding @viteReactRefresh fixed the issue, thanks!Bulldog
C
1

I see much the same with my component test ...

component is hr.tsx

export const Myhr = () => {
 return (
    <>
    <hr />
    </>
  )
};

Test program is

import { render } from '@testing-library/react';

import { Myhr } from '../components/hr.tsx'

describe('myhr test', () => {
  it("should draw line", () => {
    const { findByTestId } = render(<Myhr />);
  })
})

I see ...

FAIL  src/__tests__/hr.test.tsx [ src/__tests__/hr.test.tsx ]
Error: @vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201
 ❯ src/components/hr.tsx:1:27
      1| export const Myhr = () => {
       |                           ^
      2|  return (
      3|     <>
 ❯ src/__tests__/hr.test.tsx:3:31

The linked discussion is closed - and of little relevance

My config ...

cat vite.config.ts

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  define: {'process.argv': process.argv}, 
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './setup.js',
  }
});

grep -v ^/ setup.js | grep -v '^$'

import { afterEach, describe, expect, it, test } from 'vitest'
import { cleanup } from '@testing-library/react';
import matchers from '@testing-library/jest-dom/matchers';
expect.extend(matchers);
afterEach(() => {
  cleanup();
});

Today I ran the code again - after reinstalling npm i @vitejs/plugin-react

Today the previous error is gone - I know not why ....

Concernment answered 10/8, 2023 at 14:50 Comment(2)
I tried initiating a whole new project and that solved my issue.Forklift
Thank you! npm i @vitejs/plugin-react solved my problem as well, and I also don't know why :(Lichtenfeld
L
0

most likely versions of the packages out of sync update all vite and vitest packages to latest version, that should solve the issue

Ligulate answered 11/8, 2023 at 7:15 Comment(0)
M
0

I've been using bun for my package manager and it broke my complete vitest install.

Remove vitest and jsdom from package.json and delete node_modules folder. After that reinstall everything with either yarn or npm. This solved it for me.

Medellin answered 29/9, 2023 at 10:41 Comment(0)
M
0

I had a similar issue with my Remix 2.10.3 / 2.10.2 and 2.8.1 and turns out : The Remix Vite plugin is only intended for use in your application's development server and production builds. While there are other Vite-based tools such as Vitest and Storybook that make use of the Vite config file, the Remix Vite plugin has not been designed for use with these tools. We currently recommend excluding the plugin when used with other Vite-based tools. As "Plugin usage with other Vite-based tools (e.g. Vitest, Storybook)" section @ https://remix.run/docs/en/main/guides/vite#troubleshooting enter image description here

I had to change the remix() plugin section of the vite.config file to include !process.env.VITEST ? remix () : react() check my public repo for setup https://github.com/anyuruf/kinstree-remix

Mausoleum answered 28/7, 2024 at 12:10 Comment(0)
W
0

This will fix the issue

import { vitePlugin as remix } from "@remix-run/dev";
import { installGlobals } from "@remix-run/node";
import tsconfigPaths from "vite-tsconfig-paths";
import { defineConfig } from "vite";

installGlobals();

const MODE = process.env.NODE_ENV;

export default defineConfig({
  build: {
    cssMinify: MODE === "production",
    rollupOptions: {
      external: [/node:.*/, "stream", "crypto", "fsevents"],
    },
  },
  server: {
    watch: {
      ignored: ["**/playwright-report/**"],
    },
  },
  plugins: [
    process.env.NODE_ENV === "test"
      ? null
      : remix({
          ignoredRouteFiles: ["**/*.css"],
        }),
    tsconfigPaths(),
  ],
  test: {
    include: ["**/__tests__/**.{js,jsx,ts,tsx}"],
    environment: "jsdom",
    setupFiles: ["./tests/setup/setup-tests-env.ts"],
    restoreMocks: true,
    coverage: {
      exclude: ["**/__tests__/**"],
      include: ["app/**/*.{ts,tsx}"],
      all: true,
    },
    alias: {
      "~": "/app",
    },
  },
});

This is a typical config file

 plugins: [
    process.env.NODE_ENV === "test"
      ? null
      : remix({
          ignoredRouteFiles: ["**/*.css"],
        }),
    tsconfigPaths(),
  ],
Wersh answered 14/9, 2024 at 14:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.