Skip to content
This repository was archived by the owner on Jan 20, 2025. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 43 additions & 97 deletions docs/docs/unit-testing.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,26 @@
---
title: Unit Testing
title: 単体テスト
---

Unit testing is a great way to protect against errors in your code before you
deploy it. While Gatsby does not include support for unit testing out of the
box, it only takes a few steps to get up and running. However, there are a few
features of the Gatsby build process that mean the standard Jest setup doesn't
quite work. This guide shows you how to set it up.
単体テストは、デプロイ前のコードをエラーから守る素晴らしい手段です。Gatsby は形式にとらわれず単体テストのサポートを含んでいませんが、少しの手順で単体テストを実行できます。しかし、 Gatsby のビルドプロセスの特徴により、一般的な Jest のセットアップ方法ではうまくいきません。このガイドでは、 Jest を設定する方法を紹介しています。

## Setting up your environment
## 自分の環境を構築する

The most popular testing framework for React is [Jest](https://jestjs.io/),
which was created by Facebook. While Jest is a general-purpose JavaScript unit
testing framework, it has lots of features that make it work particularly well
with React.
もっとも人気のある React 向けのテスト用フレームワークは Facebook 製の [Jest](https://jestjs.io/ja/) です。 Jest は汎用的な JavaScript 単体テストフレームワークである一方、特に React と相性のいい特徴を数多く備えています。

_Note: For this guide, you will be starting with `gatsby-starter-default`, but the
concepts should be the same or very similar for your site._
_ヒント: このガイドでは、 `gatsby-starter-default` を使用しています。しかし、コンセプト自体はあなたのサイトと同じか、とてもよく似ているでしょう。_

### 1. Installing dependencies
### 1. 依存関係をインストールする

First, you need to install Jest and some more required packages. Install babel-jest and babel-preset-gatsby to ensure that the babel preset(s) that are used match what are used internally for your Gatsby site.
まず、 Jest といくつか必要なパッケージをインストールしましょう。 あなたの Gatsby のサイトで内部的に利用しているものと babel のプリセットが対応することを確認するために、`babel-jest` と `babel-preset-gatsby` をインストールします。

```shell
npm install --save-dev jest babel-jest react-test-renderer babel-preset-gatsby identity-obj-proxy
```

### 2. Creating a configuration file for Jest
### 2. Jest 用の設定ファイルを作成する

Because Gatsby handles its own Babel configuration, you will need to manually
tell Jest to use `babel-jest`. The easiest way to do this is to add a `jest.config.js`. You can set up some useful defaults at the same time:
Gatsby は自分自身の Babel の設定を扱っているので、あなたは自分で Jest に `babel-jest` を利用することを伝える必要があります。一番簡単な方法は、`jest.config.js` を追加することです。それと同時に、以下のような便利なデフォルトの設定ができます。

```js:title=jest.config.js
module.exports = {
Expand All @@ -50,12 +41,9 @@ module.exports = {
}
```

Go over the content of this configuration file:
この設定ファイルの中身を見てみましょう。

- The `transform` section tells Jest that all `js` or `jsx` files need to be
transformed using a `jest-preprocess.js` file in the project root. Go ahead and
create this file now. This is where you set up your Babel config. You can start
with the following minimal config:
- `transform` オプションでは、プロジェクトのルートにある `jest-preprocess.js` を使って全ての `js` または `jsx` ファイルを変換することを Jest に伝えます。`jest-preprocess.js` を作成しましょう。これは Babel の構成を設定するところです。以下のような最小の構成から初めてみましょう。

```js:title=jest-preprocess.js
const babelOptions = {
Expand All @@ -65,28 +53,15 @@ const babelOptions = {
module.exports = require("babel-jest").createTransformer(babelOptions)
```

- The next option is `moduleNameMapper`. This
section works a bit like webpack rules and tells Jest how to handle imports.
You are mainly concerned here with mocking static file imports, which Jest can't
handle. A mock is a dummy module that is used instead of the real module inside
tests. It is good when you have something that you can't or don't want to test.
You can mock anything, and here you are mocking assets rather than code. For
stylesheets you need to use the package `identity-obj-proxy`. For all other assets,
you need to use a manual mock called `file-mock.js`. You need to create this yourself.
The convention is to create a directory called `__mocks__` in the root directory
for this. Note the pair of double underscores in the name.
- 次のオプションは `moduleNameMapper` です。このオプションは、webpack のルールのように機能し、Jest にインポートを処理する方法を伝えます。Jest が扱えない静的ファイルのインポートをモックすることが、ここでの主な関心事です。モックとは、テスト内部で実際のモジュールの代わりに使用されるダミーのモジュールです。テストをしたくなかったりテストができないものをモックにすることは良いことです。どんなものでもモックにできます。ここでは、コードよりアセットをモックにしています。CSS 用に `identity-obj-proxy` というパッケージを利用する必要があります。その他全てのアセット用には、 `file-mock.js` というマニュアルのモックを利用する必要があります。これは自分自身で作成できます。`__mocks__` というディレクトリをプロジェクトルートに作成するのが慣習です。名前の前後にアンダースコアを 2 つ付与することに注意してください。

```js:title=__mocks__/file-mock.js
module.exports = "test-file-stub"
```

- The next config setting is `testPathIgnorePatterns`. You are telling Jest to ignore
any tests in the `node_modules` or `.cache` directories.
- 次は `testPathIgnorePatterns` という設定です。 `node_modules` または `.cache` ディレクトリーのあらゆるテストを無視するよう Jest に伝えます。

- The next option is very important and is different from what you'll find in other
Jest guides. The reason that you need `transformIgnorePatterns` is because Gatsby
includes un-transpiled ES6 code. By default Jest doesn't try to transform code
inside `node_modules`, so you will get an error like this:
- その次のオプションはとても重要で、他の Jest の導入ガイドの内容とは異なるものです。`transformIgnorePatterns` が必要な理由は、Gatsby がトランスパイルされていない ES6 のコードを含んでいるからです。デフォルトでは、Jest は `node_modules` 内のコードを変換しようとしません。このため、以下のようなエラーが出力されます。

```text
/my-app/node_modules/gatsby/cache-dir/gatsby-browser-entry.js:1
Expand All @@ -95,35 +70,29 @@ module.exports = "test-file-stub"
SyntaxError: Unexpected token import
```

This is because `gatsby-browser-entry.js` isn't being transpiled before running
in Jest. You can fix this by changing the default `transformIgnorePatterns` to
exclude the `gatsby` module.
これは、`gatsby-browser-entry.js` が Jest を実行する前にトランスパイルされていないからです。この解決方法は、`gatsby` のモジュールを除外するために、デフォルトの `transformIgnorePatterns` を変更することです。

- The `globals` section sets `__PATH_PREFIX__`, which is usually set by Gatsby,
and which some components need.
- `globals` オプションは、`__PATH_PREFIX__` を設定しています。これは、普段は Gatsby によって設定されるもので、いくつかのコンポーネントが必要とするものです。

- You need to set `testURL` to a valid URL, because some DOM APIs such as
`localStorage` are unhappy with the default (`about:blank`).
- `testURL` では、有効な URL を設定しましょう。 `localStorage` のような、いくつかの DOM API はデフォルト(`about:blank`)の設定では嬉しくありません。

> ヒント: あなたの Jest のバージョンが 23.5.0 以降であれば、 `testURL` のデフォルトは `http://localhost` であるので、この設定をスキップできます。

> Note: if you're using Jest 23.5.0 or later, `testURL` will default to `http://localhost` so you can skip this setting.

- There's one more global that you need to set, but as it's a function you can't
set it here in the JSON. The `setupFiles` array lets you list files that will be
included before all tests are run, so it's perfect for this.
- グローバルはもう 1 つ設定する必要があります。しかし、それは関数であるため、 JSON の中で設定できません。`setupFiles` の配列には、全てのテストが実行される前に読み込まれるファイルを列挙できます。これで完璧です。

```js:title=loadershim.js
global.___loader = {
enqueue: jest.fn(),
}
```

### 3. Useful mocks to complete your testing environment
### 3. テスト環境を完成させるための便利なモック

#### Mocking `gatsby`
#### `gatsby` をモックする

Finally, it's a good idea to mock the `gatsby` module itself. This may not be
needed at first, but will make things a lot easier if you want to test
components that use `Link` or GraphQL.
最終的に、`gatsby` モジュール自身をモックにすることは良い考えです。最初からそうする必要はないでしょう。しかし、もしあなたが `Link` や GraphQL を使っているコンポーネントをテストしたいのであれば、`gatsby` モジュールをモックにすることで、もっと簡単にテストできるようになります。

```js:title=__mocks__/gatsby.js
const React = require("react")
Expand Down Expand Up @@ -155,17 +124,13 @@ module.exports = {
}
```

This mocks the `graphql()` function, `Link` component, and `StaticQuery` component.
これは `graphql()` 関数、`Link` コンポーネント、そして `StaticQuery` コンポーネントをモックしています。

## Writing tests
## テストを記述する

A full guide to unit testing is beyond the scope of this guide, but you can
start with a simple snapshot test to check that everything is working.
単体テストの完全なガイドはこのガイドの範囲外です。しかし、全部が動いていることを確認するためにシンプルなスナップショットテストから始めることができます。

First, create the test file. You can either put these in a `__tests__`
directory, or put them elsewhere (usually next to the component itself), with
the extension `.spec.js` or `.test.js`. The decision comes down to your own
preference. In this guide, you will use the `__tests__` folder convention. To test the header component, create a `header.js` file in `src/components/__tests__/`:
まず、テスト用のファイルを作成します。テスト用のファイルは `__tests__` ディレクトリーに配置することもできますし、その他の場所(普通はコンポーネントの隣)に置くこともできます。テスト用のファイルの拡張子は `.spec.js` or `.test.js` にします。好みで決めて構いません。このガイドでは、慣習に沿って `__tests__` というフォルダーを利用します。 header コンポーネントをテストするためには、`header.js` ファイルを `src/components/__tests__/` に作成します。

```js:title=src/components/__tests__/header.js
import React from "react"
Expand All @@ -183,72 +148,53 @@ describe("Header", () => {
})
```

This is a very simple snapshot test, which uses `react-test-renderer` to render
the component, and then generates a snapshot of it on the first run. It then
compares future snapshots against this, which means you can quickly check for
regressions. Visit [the Jest docs](https://jestjs.io/docs/en/getting-started) to
learn more about other tests that you can write.
これはとてもシンプルなスナップショットテストです。`react-test-renderer` を使ってコンポーネントをレンダーし、初回の実行でコンポーネントのスナップショットを生成します。これを将来のスナップショットと比較することで、前のバージョンになかった不具合をすぐにチェックできます。他に記述できるテストを学びたい場合は、[Jestのドキュメント](https://jestjs.io/docs/ja/getting-started) をチェックしてください。

## Running tests
## テストを実行する

If you look inside `package.json` you will probably find that there is already a
script for `test`, which just outputs an error message. Change this to use the
`jest` executable that you now have available, like so:
`package.json` の中を見てみると、`test` というスクリプトはすでに存在することがわかるでしょう。これはただエラーメッセージを吐くだけです。以下のように変更し、`jest` を実行可能にしましょう。

```json:title=package.json
"scripts": {
"test": "jest"
}
```

This means you can now run tests by typing `npm test`. If you want you could
also run with a flag that triggers watch mode to watch files and run tests when they are changed: `npm test -- --watch`.
これで `npm test` を入力するとテストを実行できます。`npm test -- --watch`のように、ファイルを監視し、変更があればテストを実行する watch mode を開始するフラグを渡すこともできます。

Run the tests again now and it should all work! You may get a message about
the snapshot being written. This is created in a `__snapshots__` directory next
to your tests. If you take a look at it, you will see that it is a JSON
representation of the `<Header />` component. You should check your snapshot files
into a source control system (for example, a GitHub repo) so that any changes are tracked in history.
This is particularly important to remember if you are using a continuous
integration system such as Travis or CircleCI to run tests, as these will fail if the snapshot is not checked into source control.
今一度テストを実行してみましょう。全てうまくいくはずです!記述されたスナップショットについてのメッセージを取得しても構いません。これはテストの隣にある `__snapshots__` ディレクトリー内で作成されます。中を見てみると、 `<Header />` コンポーネントが JSON で表現されていることがわかります。過去のあらゆる変更を辿るために、スナップショットのファイルをソースコード管理システム(例:GitHub リポジトリー)に置くべきです。テストを実行するにあたり Travis や CircleCI といった CI システムを使っているのであれば、この点は特に覚えていてください。スナップショットがソース管理されていなければ、CI が落ちてしまうからです。

If you make changes that mean you need to update the snapshot, you can do this
by running `npm test -- -u`.
もしスナップショットを更新する必要があるような変更を加えるのであれば、 `npm test -- -u` を実行してください。

## Using TypeScript
## TypeScript を使う

If you are using TypeScript, you need to make two changes to your
config.
もし TypeScript を使っているなら、設定を 2 点変更する必要があります。

Update the transform in `jest.config.js` to run `jest-preprocess` on files in your project's root directory.
自分のプロジェクトのルートディレクトリー内のファイルに `jest-preprocess` を実行するために、`jest.config.js` の transform を更新してください。

**Note:** `<rootDir>` is replaced by Jest with the root directory of the project. Don't change it.
**注意:** `<rootDir>` Jest によってプロジェクトのルートディレクトリーに書き換えられるので、ここは変更しないでください。

```js:title=jest.config.js
"^.+\\.[jt]sx?$": "<rootDir>/jest-preprocess.js",
```

Also update `jest.preprocess.js` with the following Babel preset to look like this:
また、`jest.preprocess.js` を以下のような Babel プリセットに更新してください。

```js:title=jest-preprocess.js
const babelOptions = {
presets: ["babel-preset-gatsby", "@babel/preset-typescript"],
}
```

Once this is changed, you can write your tests in TypeScript using the `.ts` or `.tsx` extensions.
一度このように変更すれば、拡張子 `.ts` または `.tsx` の TypeScript でテストを記述できます。

## Other resources
## その他のリソース

If you need to make changes to your Babel config, you can edit the config in
`jest-preprocess.js`. You may need to enable some of the plugins used by Gatsby,
though remember you may need to install the Babel 7 versions. See
[the Gatsby Babel config guide](/docs/babel) for some examples.
もしあなた自身の Babel の設定に変更を加える必要があるなら、 `jest-preprocess.js` にある設定を編集できます。 Gatsby によって使われているいくつかのプラグインをオンにする必要があるでしょう。しかし、 Babel のバージョン 7 系をインストールする必要があることを覚えていてください。 [the Gatsby Babel config guide](/docs/babel) にサンプルがいくつかあります。

For more information on Jest testing, visit
[the Jest site](https://jestjs.io/docs/en/getting-started).
Jest を使ったテストをもっと知りたいのであれば、[Jestのウェブサイト](https://jestjs.io/docs/ja/getting-started)をご覧ください。

For an example encapsulating all of these techniques--and a full unit test suite with [@testing-library/react][react-testing-library], check out the [using-jest][using-jest] example.
これら全てのテクニックを隠蔽する例として、そして [@testing-library/react][react-testing-library] を使った完全な単体テスト一式の例としては、 [using-jest][using-jest] のサンプルをチェックしてください。

[using-jest]: https://github.com/gatsbyjs/gatsby/tree/master/examples/using-jest
[react-testing-library]: https://github.com/testing-library/react-testing-library