Search code examples
javascriptjestjsjsxvitevitest

"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

Solution

  • 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