0
0

More than 1 year has passed since last update.

【JavaScript】Jestの実行で「Unexpected token '('」エラーが出た話

Posted at

概要

Jestでテストを実行しようとしたところ、以下のエラーが表示されました。

C:\data\jest2\node_modules\@jest\reporters\build\GitHubActionsReporter.js:67
  #getMessageDetails (failureMessage, config) {
                     ^

SyntaxError: Unexpected token '('
    at Object.compileFunction (vm.js:344:18)
    at wrapSafe (internal/modules/cjs/loader.js:1106:15)
    at Module._compile (internal/modules/cjs/loader.js:1140:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
    at Module.load (internal/modules/cjs/loader.js:1040:32)
    at Function.Module._load (internal/modules/cjs/loader.js:929:14)
    at Module.require (internal/modules/cjs/loader.js:1080:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\data\jest2\node_modules\@jest\reporters\build\index.js:75:3)
    at Module._compile (internal/modules/cjs/loader.js:1176:30)
npm ERR! Test failed.  See above for more details.

このエラーの原因や解決方法を記載した記事がなかったので、本記事にそれらの情報を記載します。

環境

OS:Windows 10
Node.js:14.1
npm:8.15.0

原因

原因は、node.jsのバージョンが古かった事でした。
エラーが起きた箇所はGitHubActionsReporter.jsの67行目のgetMessageDetails関数です。
この箇所に記載されている内容は以下です。

GitHubActionsReporter.js
#getMessageDetails (failureMessage, config) {
    const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)(
      failureMessage
    );
    const stackLines = (0, _jestMessageUtil().getStackTraceLines)(stack);
    const topFrame = (0, _jestMessageUtil().getTopFrame)(stackLines);
    const normalizedStackLines = stackLines.map(line =>
      (0, _jestMessageUtil().formatPath)(line, config)
    );
    const messageText = [message, ...normalizedStackLines].join('\n');
    return {
      file: topFrame?.file,
      line: topFrame?.line,
      message: messageText
    };
  }

先頭に#が記載されていますが、これはprivate methodやprivate fieldを定義する記法です。
つまり、getMessageDetailsはprivate methodです。
node.jsのバージョン14.5以前では、private methodはサポートされておらず、
これらのバージョンでprivate methodが定義されたクラスを読み込もうとすると、
上記のエラーが発生します。

解決方法

private methodがサポートされているバージョンにnode.jsをバージョンアップします(14.20以降)。
https://node.green/#ES2022-features-private-class-methods

参考までに、各OSごとのNode.jsバージョンアップ方法を以下に記載します。
・Windows
https://www.suzu6.net/posts/295-node-update-windows/
・Linux、Mac
https://parashuto.com/rriver/tools/updating-node-js-and-npm

まとめ

Jestを使った記事は、どれも最近のNode.jsを使用しているので、このようなエラーが起きることもなく、結果として今回のエラーに関する情報がありませんでした。
Node.jsに限った話ではなく、ソフトウェアのバージョンを定期的にアップデートする事の大切さを痛感しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0