1
0

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】tsconfig.jsonの"types":["jest"]を設定したのにCannot find name 'describe'エラー

Posted at

はじめに

Jestのテストファイルをtypescriptで作成した際に、describetestが「Cannot find name」エラーが発生しました。原因は些細だったのですが、見落としてしまっていたため、今回備忘にしました。

問題

対象のテストファイルは以下です。コンポーネントをレンダリングするため、拡張子は.tsxです。
describetestの型定義ファイルが見つからずエラーになっています。

App.spec.tsx
import App from "@/App";
import { render, screen } from "@testing-library/react";

// エラー発生!:Cannot find name 'describe'
describe("App.tsx", () => {
  
  // エラー発生!:Cannot find name 'it'
  it("タイトル表示チェック", async () => {
    render(<App />);
    const title = await screen.findByTestId("title");
    
    // エラー発生!:Cannot find name 'expect'
    expect(title).toBeInTheDocument();
  });
});

tsconfig.jsonには"types": ["jest"]が存在しているので、グローバル変数としてjestの型定義も読み込まれているので、上記エラーは発生しないはず...!

tsconfig.json
{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ],

  "compilerOptions": {
    "esModuleInterop": true,
    "jsx": "react-jsx",
    "types": ["node", "jest", "@testing-library/jest-dom"], 
    "baseUrl": "./",
    "paths": { "@/*": ["src/*"] }
  }
}

解決方法

tsconfig.app.jsonのincludeプロパティにjest.setup.tsを含めれば解決します。

tsconfig.app.json
{
  "compilerOptions":{
      ...省略...
  }, 
-  "include": ["src"]
+  "include": ["src", "jest.setup.ts"]
}

今回、jest.setup.tsをsrcフォルダと同階層に配置していたため、typescriptのコンパイルに含まれていないことが原因でした。

おわりに

些細ですがプロジェクトのフォルダ構成によって発生する問題でもあるので、意外と見落としてしまいそうになります。注意せねば...!

参考

JISOUのメンバー募集中!

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?