0

Next.js(TypeScript)にJestを設定する方法 という記事のテストコードを参考にしたのですが、下記のエラーが出ました。

 FAIL  src/lib/__tests__/example.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/abeshmupeii/Desktop/プログラミング/typescript/portfolio/croud-next/src/lib/__tests__/example.test.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { square } from "src/lib/example";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

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

 FAIL  src/components/__tests__/Example.test.tsx
  ● 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:

    SyntaxError: /Users/abeshmupeii/Desktop/プログラミング/typescript/portfolio/croud-next/src/components/__tests__/Example.test.tsx: Support for the experimental syntax 'jsx' isn't currently enabled (6:12):

      4 | describe("Example", () => {
      5 |   it("表示されること", () => {
    > 6 |     render(<Example />);
        |            ^
      7 |     // data-testidを利用してテスト対象を抽出する方法
      8 |     expect(screen.getByTestId("Example")).toBeInTheDocument();
      9 |     expect(screen.getByTestId("Example")).toHaveTextContent("サンプル");

    Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to the 'presets' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx) to the 'plugins' section to enable parsing.

      at instantiate (node_modules/@babel/parser/src/parse-error/credentials.js:61:22)
      at instantiate (node_modules/@babel/parser/src/parse-error.js:58:12)
      at Parser.toParseError [as raise] (node_modules/@babel/parser/src/tokenizer/index.js:1736:19)
      at Parser.raise [as expectOnePlugin] (node_modules/@babel/parser/src/tokenizer/index.js:1800:18)
      at Parser.expectOnePlugin [as parseExprAtom] (node_modules/@babel/parser/src/parser/expression.js:1239:16)
      at Parser.parseExprAtom [as parseExprSubscripts] (node_modules/@babel/parser/src/parser/expression.js:684:23)
      at Parser.parseExprSubscripts [as parseUpdate] (node_modules/@babel/parser/src/parser/expression.js:663:21)
      at Parser.parseUpdate [as parseMaybeUnary] (node_modules/@babel/parser/src/parser/expression.js:632:23)
      at Parser.parseMaybeUnary [as parseMaybeUnaryOrPrivate] (node_modules/@babel/parser/src/parser/expression.js:384:14)
      at Parser.parseMaybeUnaryOrPrivate [as parseExprOps] (node_modules/@babel/parser/src/parser/expression.js:394:23)

Test Suites: 2 failed, 2 total
Tests:       0 total
Snapshots:   0 total
Time:        0.636 s
Ran all test suites related to changed files.

こちらのエラーを検索も該当するものが見つからず困っている感じです。
対処として、
yarn add @babel/preset-react --dev
yarn add @babel/plugin-syntax-jsx --dev
を行いましたが、変化は出ませんでした。
回答が分かる方がいればよろしくお願いします。

#jest.config.js 
const nextJest = require("next/jest");

const createJestConfig = nextJest({
  // next.config.jsとテスト環境用の.envファイルが配置されたディレクトリをセット。基本は"./"で良い。
  dir: "./",
});

// Jestのカスタム設定を設置する場所。従来のプロパティはここで定義。
const customJestConfig = {
  // jest.setup.jsを作成する場合のみ定義。
  // setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    // aliasを定義 (tsconfig.jsonのcompilerOptions>pathsの定義に合わせる)
    "^@/components/(.*)$": "<rootDir>/components/$1",
    "^@/pages/(.*)$": "<rootDir>/pages/$1",
  },
  testEnvironment: "jest-environment-jsdom",
};

// createJestConfigを定義することによって、本ファイルで定義された設定がNext.jsの設定に反映されます
module.exports = createJestConfig(customJestConfig);
#Example.tsx
export const Example = () => (
  <div data-testid={"Example"}>サンプルコンポーネント</div>
);
#Example.test.tsx
import { Example } from "src/components/Example";
import { render, screen } from "@testing-library/react";

describe("Example", () => {
  it("表示されること", () => {
    render(<Example />);
    // data-testidを利用してテスト対象を抽出する方法
    expect(screen.getByTestId("Example")).toBeInTheDocument();
    expect(screen.getByTestId("Example")).toHaveTextContent("サンプル");

    // テキストを利用してテスト対象を抽出する方法
    expect(screen.getByText("サンプルコンポーネント")).toBeTruthy();
  });
});
#tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "baseUrl": ".",
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "pages/register.tsx",
    "pages/login.tsx"
, "pages/post/index.tsx", "pages/home.tsx", "layouts/Cardpost.tsx", "pages/api/auth/SignUp.tsx", "pages/profile/index.tsx", "pages/post/[postId].jsx", "layouts/components/button/loginbutton.tsx"  ],
  "exclude": [
    "node_modules"
  ]
}

1 件の回答 1

1

原因は、Example.test.tsximport {Example} from "src/components/Example";が解決できてないためです。
以下のようにjest.config.jsmoduleDirectories: ['node_modules', '<rootDir>/'],を追記してください。

また、import {Example} from "../Example";と書き換えることでも解決できます。

#jest.config.js
... 省略
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  moduleNameMapper: {
... 省略

テストキャッシュクリア、テスト確認

$yarn jest test --clearCache
$yarn jest test --watch
1
  • ありがとうございます。解決することができました。 Commented 2022年8月2日 15:40

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。