I am trying to test in React application with Jest; my application uses Vite as a module bundler. The issue is, every time I run tests I get the following error:
> [email protected] test
> jest
FAIL src/test/App.test.jsx
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see for how to
enable it.
• If you are trying to use TypeScript, see
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
For information about custom transformations, see:
Details:
SyntaxError: C:\Users\Tomas\Desktop\react-test\src\test\App.test.jsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:30):
6 |
7 | test("renders content", ()=>{
> 8 | const ponent = render(<App></App>)
| ^
9 | console.log(ponent)
10 | })
Add @babel/preset-react () to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx () to the 'plugins' section to enable parsing.
at Parser._raise (node_modules/@babel/parser/src/parser/error.js:150:45)
at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:145:17)
at Parser.expectOnePlugin (node_modules/@babel/parser/src/parser/util.js:214:18)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1238:16)
at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:682:23)
at Parser.parseUpdate (node_modules/@babel/parser/src/parser/expression.js:662:21)
at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:633:23)
at Parser.parseMaybeUnaryOrPrivate (node_modules/@babel/parser/src/parser/expression.js:388:14)
at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:398:23)
at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:356:23)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.379 s
Ran all test suites.
Package.json
{
"name": "react-test",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "jest"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"jest": {
"verbose": true,
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleNameMapper": {
"\\.(gif|ttf|eot|svg|png)$": "<rootDir>/test/__mocks__/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
}
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.16.7",
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.3",
"@types/jest": "^27.4.1",
"@vitejs/plugin-react": "^1.0.7",
"jest": "^27.5.1",
"vite": "^2.8.0"
}
}
App.test.jsx
import React from "react";
import "@testing-library/jest-dom/extend-expect"
import { render } from "@testing-library/react";
import App from "../App.jsx";
test("renders content", ()=>{
const ponent = render(<App></App>)
console.log(ponent)
})
I am trying to test in React application with Jest; my application uses Vite as a module bundler. The issue is, every time I run tests I get the following error:
> [email protected] test
> jest
FAIL src/test/App.test.jsx
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to
enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
SyntaxError: C:\Users\Tomas\Desktop\react-test\src\test\App.test.jsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:30):
6 |
7 | test("renders content", ()=>{
> 8 | const ponent = render(<App></App>)
| ^
9 | console.log(ponent)
10 | })
Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
at Parser._raise (node_modules/@babel/parser/src/parser/error.js:150:45)
at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:145:17)
at Parser.expectOnePlugin (node_modules/@babel/parser/src/parser/util.js:214:18)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1238:16)
at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:682:23)
at Parser.parseUpdate (node_modules/@babel/parser/src/parser/expression.js:662:21)
at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:633:23)
at Parser.parseMaybeUnaryOrPrivate (node_modules/@babel/parser/src/parser/expression.js:388:14)
at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:398:23)
at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:356:23)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.379 s
Ran all test suites.
Package.json
{
"name": "react-test",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "jest"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"jest": {
"verbose": true,
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleNameMapper": {
"\\.(gif|ttf|eot|svg|png)$": "<rootDir>/test/__mocks__/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
}
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.16.7",
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.3",
"@types/jest": "^27.4.1",
"@vitejs/plugin-react": "^1.0.7",
"jest": "^27.5.1",
"vite": "^2.8.0"
}
}
App.test.jsx
import React from "react";
import "@testing-library/jest-dom/extend-expect"
import { render } from "@testing-library/react";
import App from "../App.jsx";
test("renders content", ()=>{
const ponent = render(<App></App>)
console.log(ponent)
})
Share
Improve this question
edited Mar 6, 2022 at 8:33
jonrsharpe
122k30 gold badges267 silver badges474 bronze badges
asked Mar 6, 2022 at 3:35
Tomi1368Tomi1368
911 gold badge1 silver badge11 bronze badges
2 Answers
Reset to default 10The error output is correct, Jest runs on your local node binary and requires that your jsx files be transformed into a syntax it can understand.
Vite does not so this transformation by default. It was designed to transpile and bundle your code into some bundle.js
that is appropriate for the browser (it can do other types of output, like libraries. You'd need to tweak your vite.config.js
).
Luckily, other folks have solved this problem for you. I'd remend using vitest, since you wouldn't need to download another transformer or invest a lot of time into setting up tricky build scripts.
Here's a guide on how to quickly set it up:
https://www.eternaldev./blog/testing-a-react-application-with-vitest/
And a migration guide:
https://vitest.dev/guide/migration.html
This is for beginner to setup from scratch with: Vite, Jest, React, Typescript
I heard Vite & Jest are not patible, to some extend.
But for me, at current stage, it seems working.(Though, I dont have in-depth knowledge on this, not sure did I miss anything.)
(if you use
npm
instead ofpnpm
, just replacepnpm add
withnpm install
, it should work)
procedure
setup Vite
choose React Typescript
install Jest & React Testing Library
pnpm create vite
pnpm add --save-dev jest @types/jest ts-jest @testing-library/jest-dom @testing-library/react @testing-library/user-event
create the main test file Greet.test.tsx
under proj-test-vitejest/src
,
make sure you import '@testing-library/jest-dom';
// import { describe, expect, test, it } from '@jest/globals'; // this doesnt work...
// import { describe, expect, test, it } from '@testing-library/jest-dom';
// import userEvent from '@testing-library/user-event';
// import '@testing-library/jest-dom/extend-expect';
// import 'jest-dom/extend-expect';
// import { Greet } from './Greet';
import '@testing-library/jest-dom';
import { render } from '@testing-library/react';
describe('Greet', () => {
test('find AA', () => {
const { getByText } = render(<div>Banana and Apple</div>);
const textElement = getByText(/Banana/); // screen.getByText(/Banana/);
expect(textElement).toBeInTheDocument();
});
test('find BB', () => {
const { getByText } = render(<div>Banana and Apple</div>);
const textElement = getByText(/Mango/);
expect(textElement).toBeInTheDocument();
});
});
now the typescript eslint, intellisense, import, should be all good
there is no need to manually change tsconfig.json
or package.json
at this point
you should not encounter issues like Property 'toBeInTheDocument' does not exist on type 'Matchers<any>' \
you should be able to find the method
toBeInTheDocument()
in
H:\Using\proj-test-vitejest\node_modules\.pnpm\@[email protected]_@[email protected][email protected]\node_modules\@testing-library\jest-dom\types\matchers.d.ts
other procedures like following are not required at this point
"types": ["node", "jest", "@testing-library/jest-dom"],
setupFilesAfterEnv: [ "<rootDir>/support/setupTests.js" ],
npm install @types/testing-library__jest-dom -D
run npx jest
, you will fail
SyntaxError: H:\Using\proj-test-vitejest\src\Greet.test.tsx: Support for the experimental syntax 'jsx' isn't currently enabled (13:12):
so
create jest.config.ts
add following to jest.config.ts
transform: {
'^.+\\.(ts|tsx|js|jsx)$': 'ts-jest',
},
Babel throwing Support for the experimental syntax 'jsx' isn't currently enabled
npx jest
try again, you fail with
Error: Jest: Failed to parse the TypeScript config file H:\Using\proj-test-vitejest\jest.config.ts
Error: Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed
so
pnpm install --save-dev ts-node
npx jest
try again, you fail with
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
Consider using the "jsdom" test environment.```
Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.
so
add following to jest.config.ts
testEnvironment: 'jsdom',
pnpm add --save-dev jest-environment-jsdom
npx jest
try again, you success now.
the results are (1 success, 1 fail (intentionally))
others
if you are tired of import '@testing-library/jest-dom';
in every test file
you can ment it out in Greet.test.tsx
// import '@testing-library/jest-dom';
create jest.setup.ts
under proj-test-vitejest/src
,
import '@testing-library/jest-dom';
// import "@testing-library/jest-dom/extend-expect";
add following to jest.config.ts
setupFilesAfterEnv: [
// '@testing-library/jest-dom',
// "@testing-library/jest-dom/extend-expect",
'<rootDir>/jest.setup.ts'
],
create Globals.d.ts
under proj-test-vitejest/src
,
import '@testing-library/jest-dom';
// import "@testing-library/jest-dom/extend-expect";
// declare module '@testing-library/jest-dom';
add following to tsconfig.json
"include": ["src", "Globals.d.ts"],
Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
overview
terminal log
PS H:\Using> pnpm create vite ../.pnpm-store/v3/tmp/dlx-5716 | +1 + ../.pnpm-store/v3/tmp/dlx-5716 | Progress: resolved 1, reused 1, downloaded 0, added 1, done √ Project name: ... proj-test-vitejest √ Select a framework: » React √ Select a variant: » TypeScript Scaffolding project in H:\Using\proj-test-vitejest... Done. Now run: cd proj-test-vitejest pnpm install pnpm run dev PS H:\Using> cd proj-test-vitejest PS H:\Using\proj-test-vitejest> pnpm add --save-dev jest @types/jest ts-jest @testing-library/jest-dom @testing-library/react @testing-library/user-event Packages: +456 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Progress: resolved 489, reused 456, downloaded 0, added 456, done dependencies: + react 18.2.0 + react-dom 18.2.0 devDependencies: + @testing-library/jest-dom 6.1.4 + @testing-library/react 14.1.2 + @testing-library/user-event 14.5.1 + @types/jest 29.5.10 + @types/react 18.2.39 + @types/react-dom 18.2.17 + @typescript-eslint/eslint-plugin 6.13.1 + @typescript-eslint/parser 6.13.1 + @vitejs/plugin-react 4.2.0 + eslint 8.54.0 + eslint-plugin-react-hooks 4.6.0 + eslint-plugin-react-refresh 0.4.4 + jest 29.7.0 + ts-jest 29.1.1 + typescript 5.3.2 + vite 5.0.3 Done in 1m 15.7s PS H:\Using\proj-test-vitejest> code . PS H:\Using\proj-test-vitejest> pnpm install --save-dev ts-node Packages: +19 -6 +++++++++++++++++++------ Progress: resolved 502, reused 469, downloaded 0, added 19, done devDependencies: + ts-node 10.9.1 Done in 2.6s PS H:\Using\proj-test-vitejest> pnpm add --save-dev jest-environment-jsdom WARN 2 deprecated subdependencies found: [email protected], [email protected] Packages: +47 +++++++++++++++++++++++++++++++++++++++++++++++ Progress: resolved 549, reused 516, downloaded 0, added 47, done devDependencies: + jest-environment-jsdom 29.7.0 Done in 3.5s PS H:\Using\proj-test-vitejest> npx jest ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft./typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information. FAIL src/Greet.test.tsx Greet √ find AA (24 ms) × find BB (6 ms) ● Greet › find BB TestingLibraryElementError: Unable to find an element with the text: /Mango/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: ments, script, style <body> <div> <div> Banana and Apple </div> </div> </body> 18 | test('find BB', () => { 19 | const { getByText } = render(<div>Banana and Apple</div>); > 20 | const textElement = getByText(/Mango/); | ^ 21 | expect(textElement).toBeInTheDocument(); 22 | }); 23 | }); at Object.getElementError (node_modules/.pnpm/@[email protected]/node_modules/@testing-library/dom/dist/config.js:37:19) at Object.<anonymous> (src/Greet.test.tsx:20:25) Test Suites: 1 failed, 1 total Tests: 1 failed, 1 passed, 2 total Snapshots: 0 total Time: 2.481 s Ran all test suites. PS H:\Using\proj-test-vitejest>
package.json
{ "name": "proj-test-vitejest", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@testing-library/jest-dom": "^6.1.4", "@testing-library/react": "^14.1.2", "@testing-library/user-event": "^14.5.1", "@types/jest": "^29.5.10", "@types/react": "^18.2.37", "@types/react-dom": "^18.2.15", "@typescript-eslint/eslint-plugin": "^6.10.0", "@typescript-eslint/parser": "^6.10.0", "@vitejs/plugin-react": "^4.2.0", "eslint": "^8.53.0", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.4", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "ts-jest": "^29.1.1", "ts-node": "^10.9.1", "typescript": "^5.2.2", "vite": "^5.0.0" } }
jest.config.ts
import type { Config } from 'jest'; export default async (): Promise<Config> => { return { // verbose: true, // roots: ['<rootDir>/src'], // , '<rootDir>/test'], // testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'], testEnvironment: 'jsdom', transform: { '^.+\\.(ts|tsx|js|jsx)$': 'ts-jest', }, setupFilesAfterEnv: [ // '@testing-library/jest-dom', // "@testing-library/jest-dom/extend-expect", '<rootDir>/jest.setup.ts' ], }; };
tsconfig.json
{ "pilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src", "Globals.d.ts"], "references": [{ "path": "./tsconfig.node.json" }] }
folder structure & image