0
0
はじめての記事投稿
Qiita Engineer Festa20242024年7月17日まで開催中!

Node.js(Express)のAPIをJestでテストする準備

Last updated at Posted at 2024-07-07

導入方法

必要なパッケージのインストール

npm install --save-dev jest ts-jest @types/jest @types/supertest

初期化

npx ts-jest config:init
The following questions will help Jest to create a suitable configuration for your project

 Would you like to use Typescript for the configuration file? ... yes
 Choose the test environment that will be used for testing » node
 Do you want Jest to add coverage reports? ... yes
 Which provider should be used to instrument code for coverage? » v8
 Automatically clear mock calls, instances, contexts and results before every test? ... yes

Node.jsの機能をテストする場合jest.config.ts ファイルを変更

 testEnvironment: "node",

package.json ファイルに追加

  "scripts": {
    "test": "jest"

describe、itなどのJestのグローバル関数をTypeScriptで使用するにはTypeScriptコンパイラがJestのグローバル関数を認識するようにします。

tsconfig.json ファイルに追加

{
  "compilerOptions": {
    "types": ["jest", "node"]
  }
}

npm run test したがエラー

Cannot find module '@/app/XXXX/page' from 'src/**tests**/components.test.tsx'

Jestが@/app/XXXX/pageモジュールを見つけることができませんというエラーが発生。これは、モジュールエイリアスが正しく設定されていないために発生することが多いです。

jest.config.tsで下記追加

  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },

これでrootディレクトリ直下の中に入っているsrcフォルダ配下のファイル全てを正しく認識します。

次はテスト終わらない問題

Jest did not exit one second after the test run has completed.

'This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

こちらの記事の通りサーバー立ち上げを app.ts から別の新しいファイルに切り出すと解消しました。

package.json"dev": の設定も変える

カバレッジレポートを見る

初期化の際にカバレッジレポートを選んでいれば勝手にcoverages/というディレクトリが生成されているが選べていなかったらコマンドを叩くようです。

npm test -- --coverage

ディレクトリから index.htmlを見つけてブラウザで開くとわかりやすく表示される

スクリーンショット 2024-07-04 231619.png

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