LoginSignup
2
4

More than 1 year has passed since last update.

【JEST導入】テストコードを書いてみよう ~環境構築とBabelの設定~

Last updated at Posted at 2021-09-12

はじめに

 最近フロントエンドの開発が多くなり、Jestでテストコードを書く機会が多くなりました。これまで、テストコードは、他のコードを真似しながら書いていたこともあり、しっかり勉強したことがありませんでした。そこで、Jestを0から学び直したいと思います。この記事は学び直しの備忘録です。

Jestとは

実行環境

  • OS: macOS Big Sur 11.5.2
  • Node.js: 14.17.6
  • npm: 6.14.15
  • jest: 27.1.1

Jestのインストール

はじめにJestを動かすためのプロジェクト(jest-basic)を作成し、npmコマンドでjestをインストールします。

terminal
$ mkdir jest-basic
$ cd jest-basic
$ npm init -y
$ npm install --save-dev jest

Testコマンドの追加

package.jsonのtestコマンドの箇所を以下のコマンドに変更します。

package.json
{
  "scripts": {
    "test": "jest"
  }
}

デフォルトのTest対象

  • 公式ドキュメントに書いてあるとおり、Jestにはtestregexというオプションがあり、この設定でどのファイルを設定テストするかを指定できます。
  • デフォルトのTest対象は、(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
  • __tests__フォルダの配下にテストを格納するか、テストのファイル名に.spec.jsまたは.test.js拡張子のファイルがテスト対象になります。
  • 公式ドキュメント testregex

Test対象のファイルを作成

Test対象のファイルをsrcフォルダを作成し、sum.jsというファイル名で足し算を行う関数を作成します。

src/sum.js
const sum = (a,b)=> a + b;

module.exports= sum;

Testファイルを作成

sum.test.jsというファイル名でtestコードを書きます。

src/sum.test.js
const sum = require("./sum");

test(`add 10 + 20 to equal 30`, () => {
  expect(sum(10, 20)).toBe(30);
});

Testを実行する

先程追加したtestコマンドを実行します。

terminal
$ npm test                   

> jest-basic@1.0.0 test /Users/jest-basic
> jest

 PASS  src/sum.test.js
  ✓ add 10 + 20 to equal 30 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.462 s
Ran all test suites.

作成したsum関数が正常に動作していることが確認できました!

Babelを使ってTestコードを書こう

  • Babelとは、JavaScriptのコンパイラです。
  • Babelを使うとよりコードをシンプルに書くことができ、ES6や7の機能を利用することができます。
  • babeljsの公式サイト

ES6の機能import関数export関数を利用する

  • Babelを利用して、ES6の機能のimport関数export関数を利用していきます。
  • 先程書いたコードを下記のように修正します。
src/sum.js
export const sum = (a,b)=> a + b;
src/sum.test.js
import { sum } from "./sum";

test(`add 10 + 20 to equal 30`, () => {
  expect(sum(10, 20)).toBe(30);
});

再度テストコマンドを実行すると、Babelを設定していないのでエラーが発生してしまいます。

terminal
$ npm test

> jest-basic@1.0.0 test /Users/jest-basic
> jest

 FAIL  src/sum.test.js
  ● 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.

Babelの導入

以下のパッケージをインストールします。

terminal
$ npm install --save-dev babel-jest @babel/core @babel/preset-env

Babelのコンフィグファイルbabel.config.jsをプロジェクト直下に作成します。

terminal
$ touch babel.config.js
babel.config.js
// babel.config.js
module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};

ES6の機能を利用したコードのテストを実行する

Babelの設定ができたので、再度テストコマンドを実行すると、コードがコンパイルされ、正常に実行できたことが確認ができます。

terminal
$ npm test

> jest-basic@1.0.0 test /Users/jest-basic
> jest

 PASS  src/sum.test.js
  ✓ add 10 + 20 to equal 30 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.657 s
Ran all test suites.
2
4
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
2
4