20

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)
2

2 Answers 2

23

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.