2

I am following the documentation at https://jestjs.io/docs/getting-started

I have a directory structure like...

learnjest/sum.js
learnjest/sum.test.js
learnjest/package.json
learnjest/package-lock.json
learnjest/node_modules

My sum.js, sum.test.js and package.json are all exact copies of the code in the "Getting Started" example.

sum.js:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

sum.test.js:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

package.json:

{
  "scripts": {
    "test": "jest"
  }
}

When I run npm test, I see...

> @ test /path/to/learnjest
> jest

/path/to/learnjest/node_modules/jest/node_modules/jest-cli/build/cli/index.js:161
    if (error?.stack) {
              ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/path/to/learnjest/node_modules/jest/node_modules/jest-cli/build/index.js:13:12)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
npm ERR! Test failed.  See above for more details.
__drush_ps1: command not found
__git_ps1: command not found
arnoldbird
  • 886
  • 1
  • 13
  • 30
  • Include the code where your error occures. – FUZIION Oct 07 '22 at 14:30
  • 5
    which node version do you use? It looks like you use optional chaining, which is supported from Node >= 14. – fjc Oct 07 '22 at 14:32
  • Does this answer your question? [Optional chaining issues when running test with jest](https://stackoverflow.com/questions/66404639/optional-chaining-issues-when-running-test-with-jest) – evolutionxbox Oct 07 '22 at 14:32
  • @fjc That was it. I needed to updated node. The test works now. Thanks. – arnoldbird Oct 07 '22 at 14:45

1 Answers1

1

The problem can occur if you are using an older version of Node.js. For example, I had the same problem with version 12. After I upgraded Node.js version to 19.2 the error was fixed.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kevin
  • 11
  • 2
  • [Optional chaining was included in Node 14.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#browser_compatibility) – Joseph Dec 10 '22 at 18:53