11

I'm going to create snapshot test, but got problems in the beginning.

I got such error while running test:

    /Users/illia/WebstormProjects/TESTS/node_modules/jest/node_modules/jest-cli/build/cli/index.js:161
    if (error?.stack) {
              ^
SyntaxError: Unexpected token '.'

In the test file I have no errors

import renderer from 'react-test-renderer';

import PaymentDisclaimer from './PaymentDisclaimer';

    it('renders correctly when all default props', () => {
        const tree = renderer.create(<PaymentDisclaimer fullPrice={9} />).toJSON();
        expect(tree).toMatchSnapshot();
    });

Packages:

"react-test-renderer": "^18.2.0",
"jest": "^29.0.3",
"ts-jest": "^29.0.1", (was installed as possible solution)
illia_6655321
  • 171
  • 1
  • 9
  • 12
    Jest 29 requires Node 14+: https://jestjs.io/blog/2022/08/25/jest-29, https://node.green/#ES2020-features-optional-chaining-operator----- – jonrsharpe Sep 14 '22 at 12:21
  • You may also check out the Jest pull request "chore: drop node 12 and 17" where support was removed. See https://github.com/jestjs/jest/pull/13033 – J-Christophe Aug 13 '23 at 04:52

2 Answers2

16

This happens when jest is running under the node version that do not read the new updates from JS. You need to run it in node 14 or higher.

Specifically, the ?. in if (error?.stack) is an optional chaining operator which is only supported in versions 14 or higher.

You can switch Node version using nvm:

$ nvm use 14 
Now using node v14.18.0 (npm v6.14.15)

check Node Version Manager (nvm)

Muhammed Moussa
  • 4,589
  • 33
  • 27
gmBarroso
  • 161
  • 1
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Albert Logic Einstein Nov 27 '22 at 14:56
  • I had the same error and I was running an old version of NodeJS installed with apt on Ubuntu 22.04. Uninstalling the old version and Installing one of the latest supported ones, as described in the main NodeJS website, solved the issue. – vinaut Jan 15 '23 at 09:34
0

I don't know why but in my case I was using nvm and I tried different versions one by one finally on node v14.12.0 the error disappeared.

Muhammad Atif
  • 101
  • 3
  • 9