Search code examples
reactjsvitest

vitest problem with the configuration file "Expression Expected" Error in React Component Testing


I'm experiencing an issue when running tests with Vitest in a React project. The test fails with an "Expression expected" error, and adding console logs in the test file does not display any output, which indicates that the test might not be running at all.

here is the vite configuration for vitest and the setupTest file

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react()],
    test: {
    globals:true,
        environment: "jsdom",
        setupFiles: ["./testSetup.js"],
    },
    server: {
        proxy: {
            "/api": {
                target: "http://localhost:3003",
                changeOrigin: true,
            },
        },
    },
});
import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";

// runs a clean after each test case (e.g. clearing jsdom)
afterEach(() => {
    cleanup();
});

the error shown in terminal is this :

Error: Expression expected
 ❯ getRollupError node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:392:41
 ❯ convertProgram node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:1056:26
 ❯ parseAstAsync node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:1898:93
 ❯ ssrTransformScript node_modules/vitest/node_modules/vite/dist/node/chunks/dep-D8YhmIY-.js:52863:11

I tried to remove globals but see this error :

 ❯ node_modules/@testing-library/jest-dom/dist/index.mjs:10:1
      8| import 'css.escape';
      9| 
     10| expect.extend(extensions);
       | ^
     11| 
 ❯ testSetup.js:3:31

also i try to replace import "@testing-library/jest-dom"; by import "@testing-library/jest-dom/vitest" but the same problem


Solution

  • Okay, I had the same issue (Error: Expression expected) and this is what fixed it. The file you are testing, and the test file, must have the same extensions.

    In my case, I had a component file named CompleteChip.jsx and a test file named CompleteChip.test.js. What fixed the error was changing the test file extension to CompleteChip.test.jsx