0
1

TypeScript + Jestをdocker環境で構築する

Last updated at Posted at 2024-04-07

はじめに

TypeScript+Jestをdocker環境で構築したときのメモ記事です。
コードをぺたぺた張っていきそこにメモを残していく。

内容

Dockerfile

イメージはnode:20を使用当時のLTS。
ENVでnode_modulesを環境変数に指定しないとTypeScriptがコンパイルできなかった。
COPY ./app/package*.json ./これがないとRUN npm install時にpackage.jsonから依存関係を取得できない。

FROM node:20

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

COPY ./app/package*.json ./

RUN npm install

docker-compose.yaml

build:contextは特に気にせずルートディレクトリ、Dockerfileを使うのでdockerfileも追加
tty:コンテナの終了を防ぐ。
volumes:localの内容をすぐにコンテナ環境に反映するため。node_modulesをマウントの対象から外すために/app/node_modulesを記述。
woring_dir:DockerfileでWORKDIR書いてるからいらないかも?

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    tty: true
    volumes:
      - ./app:/app
      - /app/node_modules
    working_dir: /app

package.json

jestのところだけメモ。
transform:テストファイルが実行される前に特定の処理を行う。.ts,.tsxの拡張子にts-jestを適用する。
ts-jestは、JestをTypeScriptに対応させるためのものです。ts-jestを入れると、TypeScriptで書いたテストコードを、コンパイルの手間なしにそのまま実行できるようになる。

testRegex:テストと認識するファイルを正規表現で定義。今回はtestsディレクトリ内のすべてのファイルもしくは特定の拡張子の場合。

{
    "name": "typescript-jest-app",
    "version": "1.0.0",
    "description": "",
    "scripts": {
      "test": "jest"
    },
    "dependencies": {
      "@types/jest": "^26.0.23",
      "jest": "^26.6.3",
      "ts-jest": "^26.5.6",
      "typescript": "^4.2.4"
    },
    "jest": {
      "transform": {
        "^.+\\.tsx?$": "ts-jest"
      },
      "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
      "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
      ]
    }
  }

GitHub

追記

TypeScriiptだけでなにかアプリを作るのは難しいので、
別記事でフレームワークを使ったJest環境の記事を作るかも

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