90302
[Next.js(TypeScript)にJestを設定する方法](https://nishinatoshiharu.com/install-jest-
in-next/) という記事のテストコードを参考にしたのですが、下記のエラーが出ました。

```

     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"
      ]
    }
    
```
CC BY-SA 4.0
2022-08-01T00:37:25.740
90298
2022-08-01T14:32:58.593
2022-08-01T14:32:58.593
3060
52921
question
reactjs next.js jestjs
Next.jsでJestを使用したテストを行うとエラーがでる
原因は、`Example.test.tsx`の`import {Example} from
"src/components/Example";`が解決できてないためです。  
以下のように`jest.config.js`へ`moduleDirectories: ['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
    
```
CC BY-SA 4.0
2022-08-01T05:05:28.553
90302
2022-08-01T05:05:28.553
14890
90298
answer