I am setting up Jest & React Testing Library in Next.js 12.1.6, using the new Rust compiler setup, as described here. Jest-only testing is fine, but when I try to render a component in my test file, I get an error:
"Support for the experimental syntax 'jsx' isn't currently enabled (11:12)"
My understanding of how Next.js and/or Babel and Jest all work together under the hood is sketchy at best, but the way I understand it, Babel is bypassed when using the Next.js 12 Rust compiler. I figure that the JSX is supposed to be transformed by Next before it gets to Jest, and I figure that this is not happening. I have no idea what additional configuration I could even attempt in order to fix this. I can't find any hints online, and nobody else seems to be having the same problem. I have read numerous articles and watched a plethora of videos featuring people breezing through the same setup. I have retraced their steps to no avail.
So, I decided to try and set Jest up to use Babel for the transformation, keeping the existing configuration and adding a .babelrc file:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
and then adding the following line to my customJestConfig in jest.config.js (and installing the appropriate modules, of course.
transform: {"\\.[jt]sx?$": "babel-jest"}
I don't know whether this idea was sensible or comical, but either way it didn't work.
How can I resolve this situation so that I am able to use JSX with Jest & Testing Library using the Rust compiler setup?
// package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.1.6",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-redux": "^7.2.6",
"@reduxjs/toolkit": "^1.7.2",
"next-redux-wrapper": "^7.0.5"
},
"devDependencies": {
"@types/node": "18.0.0",
"@types/react": "18.0.14",
"@types/react-dom": "18.0.5",
"eslint": "8.18.0",
"eslint-config-next": "12.1.6",
"typescript": "4.7.4",
"jest": "28.1.1",
"@types/jest": "28.1.2",
"jest-environment-jsdom": "28.1.1",
"@testing-library/jest-dom": "5.16.4",
"@testing-library/react": "13.3.0",
"@testing-library/user-event": "14.2.1"
}
}
// jest.config.js
import nextJest from "next/jest";
const createJestConfig = nextJest({dir: '.'})
const customJestConfig = {
testEnvironment: "jest-environment-jsdom",
clearMocks: true,
moduleDirectories: ["node_modules", "<rootDir>/"],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
transform: {"\\.[jt]sx?$": "babel-jest"}
}
export default createJestConfig(customJestConfig)
// jest.setup.js
import "@testing-library/jest-dom/extend-expect"
// example-test.test.tsx
import {render, screen} from "@testing-library/react"
import userEvent from "@testing-library/user-event";
import Home from "../pages/index"
it("renders Home", function () {
render(<Home />)
const heading = screen.getByRole('heading', {
name: /test/i,
})
expect(heading).toBeInTheDocument()
})