📝
Jest v28 で発生する Jest encountered an unexpected token の調査
Jest v27 から v28 へのアップデート対応時に以下のエラーに遭遇しました。
● 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
Jest v28 では package.json の exports
フィールドがサポートされました。更に testEnvironment
に応じて挙動が変わるようになっています。
この変更により利用している npm package によっては Jest encountered an unexpected token
エラーが発生する場合があります。
以下のサンプルリポジトリでは firebase@9.16.0
を利用したテストコードでエラーが発生します。
firebaseErrorMessage.ts
import { FirebaseError } from "firebase/app";
import { AuthErrorCodes } from "firebase/auth";
export const firebaseErrorMessage = (error: FirebaseError) => {
switch (error.code) {
case AuthErrorCodes.INVALID_EMAIL:
return "invalid email";
default:
return error.message;
}
};
firebaseErrorMessage.test.ts
import { FirebaseError } from "firebase/app";
import { AuthErrorCodes } from "firebase/auth";
import { firebaseErrorMessage } from "./firebaseErrorMessage";
describe(firebaseErrorMessage.name, () => {
test("invalid email", () => {
const error = new FirebaseError(AuthErrorCodes.INVALID_EMAIL, "");
expect(firebaseErrorMessage(error)).toBe("invalid email");
});
});
package.json の exports
を参照する挙動ですが testEnvironmentOptions
で設定可能となっています。
今回の firebase@9.16.0
の場合は以下のように customExportConditions
を設定し node
も参照するように設定することで Jest encountered an unexpected token
エラーは発生しなくなります。
jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
testEnvironmentOptions: {
customExportConditions: ["browser", "node"]
},
};
まとめ
Jest v28 へのアップデートで Jest encountered an unexpected token
エラーが発生した場合は package.json の exports
サポートが影響している可能性があります。
その場合は customExportConditions
による調整で通るようになる場合があります。
ちなみにサンプルリポジトリで発生していたエラーは firebase の以下の Pull Request によって解消されており firebase@9.17.0
以降であれば発生しません。
Discussion