Compile JSX in @swc/jest Tests

Here's how to compile JSX in jest tests that use SWC, or Speedy Web Compiler.


Wellll, this is an article about a toolchain that's getting a little long. Of course, not as bad as it could be. We have only one babel plugin here, after all.

npm install jest @swc/core @swc/jest @babel/core @babel/plugin-transform-react-jsx

So what's all this for? @swc/core is supposed to be a faster compiler. Faster than Babel. And when you start compiling things in test files, you need to run those files through @swc/jest. That should be a drop-in replacement. Babel is still used, however, providing the ability to transform the JSX.

Set up SWC

To control SWC, implement a .swcrc file:

 "$schema": "",
 "jsc": {
   "parser": {
     "syntax": "ecmascript",
     "jsx": true

Set up Babel

To control babel, implement a babel.config.js file:

export default {
  plugins: ["@babel/plugin-transform-react-jsx"],

Now why does one need to configure babel to transform jsx and swc to transform jsx? I'm not sure. But it doesn't seem to work with just one or the other.

Set up Jest

To control jest, implement a jest.config.js file:

export default {
  transform: {
    "^.+\\.(t|j)sx?$": ["@swc/jest"],

Write some JSX Code

Want some JSX, right? Write it in stuff.js:

import React from 'react'

function MyComponent() {
  return <div>yay</div>

export function add(a, b) {
  return a + b

Write a Test

And then the test in a stuff.test.js file:

import { add } from './stuff.js'

it('adds', () => {
  expect(add(1, 2)).toEqual(3)

Note that the test exercising the add function, which is not JSX. But the import is for a file that contains jsx, so to eval the file, compilation is required.

The Error to Avoid

If you don't compile, you'll get a stinker error like this:


 FAIL  src/stuff.test.js
  ‚óŹ Test suite failed to run

      x Expression expected
     5 |   return 
: ^ ...

Which, of course, will let your beautiful code run through this chain of configured magic boxes, then run in your jest test environment perfectly forever (or until the next library upgrade).

No errors. Compiled JSX. Call it a day, you JavaScript fiend.