1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jest encountered an unexpected token に向き合う

Posted at

はじめに

JISOU で Vite + Rreact の環境に Jest でテストを書こう!という課題がありました。設定は難しいため、設定ファイルは課題の中に記載がありました。物好きなわたしは Jest の本家サイトからインストール手順を追いかけてみて、見事にエラーに出くわしたのでそれを記事にしました。

:warning: react testing library は未インストールです。

エラー

抜粋

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

(略)

If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript

(略)
   
/Users/akira/Project/private/vite-ts/__test__/sum.test.ts:1
  ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import sum from './sum';
                                                                                    ^^^^^^

本文
  FAIL  __test__/sum.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/akira/Project/private/vite-ts/__test__/sum.test.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import sum from './sum';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.146 s

Jest で理解できない文法があり、そのためエラーになったようです。本家サイトでも

Jest はプロジェクト内のコードを JavaScript として実行しますが、Node でサポートされていない構文 (JSX、TypeScript、Vue のテンプレート) を使用している場合は、ブラウザ用にビルドする場合と同様に、コードをプレーンな JavaScript に変換する必要があります。

掲載ページ

と説明があり TypeScript を使う場合には工夫が必要です。取り組んだことはパッケージのインストールと設定ファイルの追加です。

取り組み

先程のエラー本文には

If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript

とあり TypeScript での対応が書いてあります。

npm install --save-dev ts-jest

@babel/preset-typescript はインストールしません。
型チェックが行われません。

設定ファイルも必要になります。こちらを実行すると

npx ts-jest config:init

jest.config.js を生成してくれました。

/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
  testEnvironment: "node",
  transform: {
    "^.+.tsx?$": ["ts-jest",{}],
  },
};

jest.config.js がない場合 Jest は文法を理解できず冒頭のエラーになります。

transform がキモで tsx ファイルを ts-jest を使ってトランスパイルしてくれます。

気づき

Javascript で Jest を使うときは describe / expect などテストに必要なものはグローバルで使えていますが、TypeScript では使えません。TypeScript でも descripbe / expect を使うには @types/jest が必要です。

npm install --save-dev @types/jest

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?