Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"describe is not defined" in Vitest

I'm starting out with Vite for a React application but unable to get jest tests working. I am trying to use Vitest with experimental ES module.

I am getting:

FAIL  src/App.test.tsx [ src/App.test.tsx ]
ReferenceError: describe is not defined

I have added Jest, Mocha Vite, and Vitest, but it hasn't helped.

My package.json has

  "devDependencies": {
    "@testing-library/react": "^14.0.0",
    "@types/jest": "^29.5.0",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "@vitejs/plugin-react-swc": "^3.0.0",
    "jest": "^29.5.0",
    "mocha": "^10.2.0",
    "typescript": "^4.9.3",
    "vite": "^4.2.0",
    "vitest": "^0.29.8"
  }

My Vite config is:

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

export default defineConfig({
  plugins: [react()],
}

My Vitest config is:

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

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
  },
})

This is from running Vitest. If I run Jest directly with

jest

or

node --experimental-vm-modules node_modules/jest/bin/jest.js 

I get:

 SyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx: 
 Support for the experimental syntax 'jsx' isn't currently enabled
like image 254
Michael Durrant Avatar asked Sep 10 '25 04:09

Michael Durrant


2 Answers

your test code is using global mode you must enable it:

vitest.config.ts

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

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
    globals: true
  },
})

also if you are using typescript you need to add styles to benefit the hint: tsconfig.json

{
  ...
  "compilerOptions": {
    ...
    "types": ["vitest/globals"]
  }
}

Although vitest APIs are designed to be jest friendly, it doesn't mean jest can run test code written for vitest

like image 172
Tachibana Shin Avatar answered Sep 12 '25 18:09

Tachibana Shin


To summarise the answers and the documentation

(Unlike some other test frameworks) vitest does not globally define its test functions.

You can either:

Explicitly import the functions you need in each test file:

import { describe, test, expect } from 'vitest';

or use vitest.config.ts to configure it globally

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true
  }
})
like image 41
Jason Avatar answered Sep 12 '25 17:09

Jason