Jest SyntaxError: Unexpected token <
Asked Answered
P

3

20

I'm want to test a component in a React app using Jest Enzyme with TypeScript. I follow the instructions on the Jest site, but for some reason I get:

SyntaxError: Unexpected token <

I can test test some functions. There isn't any problem with that, but when I use a component, I get an error.

This is the Jest configuration in file package.json:

"jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testMatch": ["**/__tests__/*.(ts|tsx)"],
    "snapshotSerializers": ["enzyme-to-json/serializer"],
    "setupFilesAfterEnv": ["<rootDir>/src/setupEnzyme.ts"],
    "unmockedModulePathPatterns": ["node_modules/react/", "node_modules/enzyme/"]
  }

Enzyme configuration

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
export default class TesComponent extends Component {
    render(){
        return (
            <div>test</div>
        )
    }
}
import { shallow } from 'enzyme'
import TestCompoenent from '../TestComponent'

test('component testing', () => {
    const component = shallow(<TestCompoenent />)
    expect(component.contains(<div>test</div>)).toBeTruthy()
})

This is the error:

Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g., it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • 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/en/configuration.html

    Details:

    /home/user/Documents/local-platform/frontend/src/pages/__tests__/settigs.test.tsx:9
        var component = enzyme_1.shallow(<TestComponent_1.default />);
                                         ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

I expect for the tests to pass, because Test Component does include <div>test</div>.

Penton answered 28/6, 2019 at 11:33 Comment(6)
Post your TestCompoenent also.Indubitability
i've edited postPenton
Try jest --clearCacheIndubitability
got the same error:(Penton
Any solutions for NextJs?Bahner
One line says "TesComponent", without "t" (export default class TesComponent), another says "TestCompoenent", an extra "e" (import TestCompoenent from '../TestComponent'), and yet another "TestComponent". Which one is it????Bewray
B
32

Try changing tsconfig.json

"jsx": "preserve" -> "jsx": "react"

Brest answered 18/6, 2020 at 8:45 Comment(3)
This option specifies how the output should be generated(i.e. JSX syntax converted to, type checking). Details typescriptlang.org/docs/handbook/jsx.html#basic-usageBrest
Finally!! Just in case, changing it to "react" fixed my main issue. However, it throws some other errors. Solved by replacing it with react-jsx, as mentioned by Dan Barclay (https://mcmap.net/q/75338/-39-react-39-refers-to-a-umd-global-but-the-current-file-is-a-module)Jordans
This is not working in nextjs. - jsx was set to preserve (next.js implements its own optimized jsx transform)Oribelle
L
5

Adding the @babel/plugin-transform-react-jsx as plugin to babel in babel.config.js resolved this issue for me.

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
  plugins: ['@babel/plugin-transform-react-jsx'],
};

I hope that will be helpful to anyone. Spent a few hours trying different approaches before finding that

Louque answered 25/5, 2023 at 13:50 Comment(1)
would have been useful if you had shared where you found that :-)Grubman
I
2

It seems that your configuration does not process the TypeScript file (.tsx) properly.

Here is part of my working configuration:

"jest": {
    "transform": {
       "^.+\\.tsx?$": "ts-jest",
    },
    "moduleFileExtensions": [
       "ts",
       "tsx",
       "js",
       "json"
    ],
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupSpecs.ts"
}

I have used setupTestFrameworkScriptFile instead of setupFilesAfterEnv.

Impel answered 28/6, 2019 at 11:52 Comment(4)
i get message saying Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths, when i press enter to continue i get the same errorPenton
how about adding "moduleFileExtension" ?Merlinmerlina
please provide test repo, with miniam l package json, jest config, and those 2 simple tsx filesMerlinmerlina
Please see my answer. https://mcmap.net/q/662731/-in-jest-test-enzyme-shallow-throws-unexpected-token-lt-errorRettarettig

© 2022 - 2024 — McMap. All rights reserved.