> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quiesco.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# チュートリアル：CucumberでToDoアプリをテストする

> 3画面の小さなToDoアプリにE2Eテストを一歩ずつ書いていきます。テストID、画面をまたぐフロー、バックドア、リセット、失敗の読み方。

このページでは、[ToDoアプリのチュートリアル](https://docs.quiesco.dev/ja/tutorial.md)の8つのテストを**Cucumber**で書きます。先にそちらで[アプリ](https://docs.quiesco.dev/ja/tutorial.md#the-app)を確認し、[プロジェクトを用意](https://docs.quiesco.dev/ja/tutorial.md#get-the-project)してください。同じテストの[Vitest](https://docs.quiesco.dev/ja/tutorial-vitest.md)版と[Jest](https://docs.quiesco.dev/ja/tutorial-jest.md)版もあります。

## テストファイル

[`todo-tutorial-cucumber`](https://github.com/h2nology/quiesco/tree/main/examples/todo-tutorial-cucumber)では、`cucumber.mjs`が、Quiescoを登録する`features/support/quiesco.ts`とステップ定義を読み込みます（[Cucumber](https://docs.quiesco.dev/ja/cucumber.md)）。シナリオは`features/list.feature`と`features/detail.feature`に、ステップは`features/step_definitions/todo.steps.ts`にあります。ステップは`this.app`からアプリを操作します。一緒に進めるなら、3つのファイルを空にして、読みながら各シナリオとそのステップを追加してください。

## ステップ1：要素にテストIDを付ける

テストは要素を`testID`で見つけます。テストの中の単なる文字列はテストIDです。`app.tap('add-todo')`は`testID="add-todo"`の要素をタップします。このアプリは、テストが操作または確認するすべての要素にテストIDを付けています。

| 画面 | `testID` | 要素 |
| - | - | - |
| リスト | `todo-list-screen` | 画面そのもの |
| | `empty-state` | リストが空のあいだ表示される「Nothing to do」 |
| | `todo-summary` | 「1 of 2 done」 |
| | `todo-row`、`todo-title`、`todo-checkbox` | 各行、そのタイトル、そのチェックボックス |
| | `add-todo` | New todoボタン |
| 新規ToDo | `new-todo-screen`、`title-input`、`notes-input`、`title-error`、`save-todo` | 画面、入力欄、タイトルの下のエラー、Save |
| 詳細 | `todo-detail-screen`、`detail-title`、`detail-notes`、`todo-status` | 画面、テキスト、Open / Doneバッジ |
| | `toggle-done`、`delete-todo` | 2つのボタン |

コード上では、テストIDはpropが1つ増えるだけです（`src/components/TodoRow.tsx`）。

```tsx theme={null}
<View testID="todo-row" style={styles.row}>
  <Checkbox testID="todo-checkbox" checked={todo.done} onToggle={onToggle} label={…} />
  …
</View>
```

どの行も同じIDを持つので、テストは位置（`{ id: 'todo-title', index: 0 }`は一番上の行）かテキスト（`{ text: 'Buy milk' }`）で1行を選びます。アプリの実行中に`npx quiesco tree`を使うと、すべてのIDを含む要素ツリーが出力されるので、既存のアプリに付いているIDを探せます。

## ステップ2：最初のテスト

まずは、起動直後に表示されるものを確認します。

```gherkin features/list.feature theme={null}
Feature: The todo list

  Scenario: A fresh start shows the empty list
    Then the list is empty
```

```ts features/step_definitions/todo.steps.ts theme={null}
import { type DataTable, Given, Then, When } from '@cucumber/cucumber';
import type { QuiescoWorld } from '@quiesco/cucumber';

import type { SeedTodo } from '../../src/backdoors.ts';

Then('the list is empty', async function (this: QuiescoWorld) {
  await this.app.expectVisible('empty-state');
  await this.app.expectCount('todo-row', 0);
});
```

`this.app`はテスト対象のアプリを操作するドライバーです。ステップはユーザーの操作と確認としてそのまま読め、テストIDはステップ定義の中にとどまります（`Given`、`When`、`DataTable`、`SeedTodo`は後のステップで使います）。

Webで実行してみましょう。

```sh theme={null}
npx playwright install chromium

# EXPO_PUBLIC_QUIESCO=1でWebビルドをエクスポートしてから quiesco test --platform web
npm run e2e:web
```

初回の実行ではChromiumが起動してアプリを開き、数秒でテストが通ります。同じファイルをiOSとAndroidで実行するのは[ステップ7](#step-7-ios-and-android)です。

## ステップ3：画面をまたぐフロー

次は、ユーザーと同じ手順でToDoを追加します。フォームを開き、入力し、保存して、リストを確認します。

```gherkin features/list.feature theme={null}
  Scenario: A new todo appears at the top of the list
    When I add a todo "Buy milk" with the notes "Oat milk, 1 l"
    Then the first todo is "Buy milk"
    And the summary reads "0 of 1 done"
```

```ts features/step_definitions/todo.steps.ts theme={null}
When('I add a todo {string} with the notes {string}', async function (this: QuiescoWorld, title: string, notes: string) {
  await this.app.tap('add-todo');
  await this.app.expectVisible('new-todo-screen');

  await this.app.type('title-input', title);
  await this.app.type('notes-input', notes);
  // 保存に600 msかかり、その後リストに戻る。Quiescoはその両方を待つので、sleepは不要。
  await this.app.tap('save-todo');

  await this.app.expectVisible('todo-list-screen');
});

Then('the first todo is {string}', async function (this: QuiescoWorld, title: string) {
  await this.app.expectText({ id: 'todo-title', index: 0 }, title);
});

Then('the summary reads {string}', async function (this: QuiescoWorld, summary: string) {
  await this.app.expectText('todo-summary', summary);
});
```

このテストには`sleep`も`waitFor`もありません。それでも、どの行も時間のかかる処理に依存しています。`tap('add-todo')`の後の画面遷移、600 msの保存タイマー、リストへ戻る遷移です。Quiescoは呼び出しの前後に毎回、アプリが**アイドル**になる（保留中のタイマー、リクエスト、レンダリング、アニメーションがなくなる）のを待つので（[同期](https://docs.quiesco.dev/ja/sync.md)）、各行は前の行が終えた状態から始まります。アサーションも、条件が満たされるかタイムアウトするまで再試行します。

`expectVisible('new-todo-screen')`はテストを通すためには不要ですが、失敗したときにわかりやすくなります。ボタンを押してもフォームが開かなくなった場合、テストは`type`ではなくこの行で失敗します。

## ステップ4：問題があるときにユーザーが見るもの

フォームは、タイトルのないToDoを保存しません。エラーが表示されてフォームが開いたままになることを確認し、それから戻ります。

```gherkin features/list.feature theme={null}
  Scenario: A todo needs a title
    When I save a new todo without a title
    Then the form says "Enter a title"
    When I go back
    Then the list is empty
```

```ts features/step_definitions/todo.steps.ts theme={null}
When('I save a new todo without a title', async function (this: QuiescoWorld) {
  await this.app.tap('add-todo');
  await this.app.tap('save-todo');
});

Then('the form says {string}', async function (this: QuiescoWorld, error: string) {
  await this.app.expectText('title-error', error);
  await this.app.expectVisible('new-todo-screen');
});

When('I go back', async function (this: QuiescoWorld) {
  // ユーザーと同じ方法で戻る：プラットフォームに応じて戻るボタン、ブラウザーの戻る、スワイプ。
  await this.app.goBack();
});
```

`goBack()`は、そのプラットフォームでの通常の方法で戻ります。Androidは戻るボタン、Webはブラウザーの戻る、iOSはナビゲーションバーの戻るボタンです。1行で3つすべてに対応できます。

## ステップ5：バックドアでデータから始める

詳細画面のテストには、リストにToDoが必要です。テストごとにフォームから入力しても動きますが、遅いうえに、ToDoの削除についてのテストがフォームの不具合でも失敗してしまいます。**バックドア**は、アプリがテスト用にだけ登録する関数です。テストはこれを呼んで、状態を直接用意します。

アプリとテストの両方がコンパイルするファイル（`src/backdoors.ts`）で一度だけ宣言します。

```ts theme={null}
export interface SeedTodo {
  title: string;
  notes?: string;
  done?: boolean;
}

declare module '@quiesco/agent' {
  interface Backdoors {
    /** リストをこれらのToDoで置き換える（先頭の要素が一番上）。 */
    seedTodos: (todos: SeedTodo[]) => void;
  }
}
```

登録は`src/e2e.ts`で行います。このファイルは`_layout.tsx`がe2eビルドでだけ読み込むので、中身は本番には一切入りません。

```ts theme={null}
import { quiesco } from '@quiesco/agent';

import type {} from './backdoors';
import { todoStore } from './store';

quiesco.backdoor('seedTodos', (todos) => {
  todoStore.replaceAll(todos);
});
```

```tsx theme={null}
// src/app/_layout.tsx
if (process.env.EXPO_PUBLIC_QUIESCO === '1') {
  require('../e2e');
}
```

これで、詳細画面のテストは2件のToDoがある状態から始められます。

`Background`は、そのフィーチャーの各シナリオの前に実行されます。

```gherkin features/detail.feature theme={null}
Feature: Todo details

  Background:
    Given these todos:
      | title            | notes         |
      | Buy milk         | Oat milk, 1 l |
      | Call the dentist |               |

  Scenario: A todo opens on its own screen
    When I open the todo "Buy milk"
    Then I see the details of "Buy milk" with the notes "Oat milk, 1 l"
    When I go back
    Then I see the list

  Scenario: Marking a todo done shows in the list
    When I open the todo "Call the dentist"
    And I mark it as done
    Then its status is "Done"
    When I go back
    Then todo 2 is checked
    And todo 1 is not checked
    And the summary reads "1 of 2 done"

  Scenario: The checkbox in the list toggles a todo
    When I check todo 1
    Then todo 1 is checked
    And the summary reads "1 of 2 done"

  Scenario: Deleting a todo goes back to the list without it
    When I open the todo "Buy milk"
    And I delete it
    Then I see the list
    And the list has 1 todo
    And there is no todo "Buy milk"
```

```ts features/step_definitions/todo.steps.ts theme={null}
Given('these todos:', async function (this: QuiescoWorld, table: DataTable) {
  // 空のセルは空文字列になるので、そのときはnotesを省く。
  const todos: SeedTodo[] = table.hashes().map(({ title, notes }) => (notes ? { title, notes } : { title }));
  await this.app.backdoor('seedTodos', todos);
});

When('I open the todo {string}', async function (this: QuiescoWorld, title: string) {
  await this.app.tap({ text: title });
  await this.app.expectVisible('todo-detail-screen');
});

Then('I see the details of {string} with the notes {string}', async function (this: QuiescoWorld, title: string, notes: string) {
  await this.app.expectText('detail-title', title);
  await this.app.expectText('detail-notes', notes);
});

Then('I see the list', async function (this: QuiescoWorld) {
  await this.app.expectVisible('todo-list-screen');
});

When('I mark it as done', async function (this: QuiescoWorld) {
  await this.app.tap('toggle-done');
});

Then('its status is {string}', async function (this: QuiescoWorld, status: string) {
  await this.app.expectText('todo-status', status);
});

When('I check todo {int}', async function (this: QuiescoWorld, n: number) {
  await this.app.tap({ id: 'todo-checkbox', index: n - 1 });
});

Then('todo {int} is checked', async function (this: QuiescoWorld, n: number) {
  await this.app.expectChecked({ id: 'todo-checkbox', index: n - 1 });
});

Then('todo {int} is not checked', async function (this: QuiescoWorld, n: number) {
  await this.app.expectNotChecked({ id: 'todo-checkbox', index: n - 1 });
});

When('I delete it', async function (this: QuiescoWorld) {
  await this.app.tap('delete-todo');
});

Then('the list has {int} todo(s)', async function (this: QuiescoWorld, count: number) {
  await this.app.expectCount('todo-row', count);
});

Then('there is no todo {string}', async function (this: QuiescoWorld, title: string) {
  await this.app.expectNotExists({ text: title });
});
```

宣言があるので（ステップファイルが`src/backdoors.ts`をインポートしています）、`this.app.backdoor('seedTodos', …)`は型チェックされます。名前のスペルミスやタイトルのないToDoは、ステップのTypeScriptエラーになります。

`{ text: 'Buy milk' }`はユーザーが読む文字で要素を見つけます。`expectChecked`はチェックボックスの`accessibilityState`を読みます。スクリーンリーダーが読み上げるのと同じ状態です。

## ステップ6：どのテストもきれいな状態から始まる

Quiescoはテストの前に毎回アプリを**ソフトリセット**します。ストレージを消去し（iOS / AndroidではAsyncStorage、WebではlocalStorage、sessionStorage、IndexedDB）、ナビゲーションを最初の画面に戻して、アプリを再マウントします。アプリを再起動するよりずっと高速です。

再マウントではJavaScriptのモジュールの状態は消えません。このアプリはToDoをモジュール変数に保持しているので、`src/e2e.ts`ではその消し方もQuiescoに伝えています。

```ts theme={null}
// Quiescoはテストの前に毎回アプリをソフトリセットする：ストレージを消去し、アプリを再マウントする。
// ToDoはモジュール変数にあり、再マウントでは残るので、ここで消去する。
quiesco.onReset(() => {
  todoStore.replaceAll([]);
});
```

もう1つのテストでこれを確認します。

`features/detail.feature`の`Background`はそこのすべてのシナリオにデータを用意するので、このシナリオは`features/list.feature`の最後、ToDoを追加するシナリオの後に置きます。

```gherkin features/list.feature theme={null}
  Scenario: Every scenario starts with an empty list
    # 上のシナリオはToDoを残したが、ソフトリセットとsrc/e2e.tsのonResetフックがそれを消去した。
    Then the list is empty
```

`onReset`フックを外すと、このテストは直前のテストのToDoが画面に残ったまま失敗します。Reactとストレージの外にある状態（モジュール変数、React Queryのクライアントのようなキャッシュ、インメモリーのデータベースなど）には、`onReset`フックが必要です。

## ステップ7：iOSとAndroidで実行する

テストは変更しません。プラットフォームごとにe2eアプリを一度ビルドして、同じファイルを実行します。

> [tab] iOS
>
> ```sh theme={null}
> # 先にシミュレーターを起動しておく：open -a Simulator
>
> # EXPO_PUBLIC_QUIESCO=1でprebuildしてxcodebuild：初回は数分かかる
> npm run e2e:build:ios
>
> npm run e2e:ios
> ```

> [tab] Android
>
> ```sh theme={null}
> # 先にエミュレーターを起動しておく：Android StudioのDevice Manager、または emulator -avd <name>
>
> # EXPO_PUBLIC_QUIESCO=1でprebuildして gradlew assembleDebug：初回は数分かかる
> npm run e2e:build:android
>
> npm run e2e:android
> ```

`quiesco test`はビルドをインストールし、dev client用にMetroを起動し、テストを実行してからMetroを停止します。iOSとAndroidでは、`tap`と`type`はコンポーネントの呼び出しではなく、実際のタッチとキーボード入力です。キーボードや別のビューに覆われたボタンは、ユーザーが押せないのと同じように、テストを失敗させます（`ELEMENT_OBSCURED`）。

## テストが失敗したとき

ステップ3の`Then the first todo is "Buy milk"`を`Then the first todo is "Buy bread"`に変えて、もう一度テストを実行してみてください。テストはアサーションのタイムアウト後に失敗し、期待した値、実際の値、アプリがどこにいたかを示します。

```text theme={null}
QuiescoError: expect text failed after 10000ms for { id: "todo-title", index: 0 }: expected "Buy bread", actual "Buy milk" (current route: /)

Quiesco evidence:
  artifacts/20261123-212209-web/001-a-new-todo-appears-at-the-top-of-the-list/failure.png
  artifacts/20261123-212209-web/001-a-new-todo-appears-at-the-top-of-the-list/elements.json
  …
```

`artifacts/`フォルダーには、失敗したテストごとに次のファイルがあります。

| ファイル | 内容 |
| - | - |
| `failure.png` | 失敗時の画面。失敗した呼び出しの対象要素が赤枠で囲まれる |
| `elements.json` | 現在のルートと、テストID、ラベル、テキストを持つすべての要素。表示されているかどうかとその理由も含む |
| `element-tree.json` | 要素ツリー全体 |
| `idle-state.json` | アイドル待ちがタイムアウトしたとき、何がビジーだったか |
| `timeline.html` | テストのすべての呼び出しと、その所要時間、アプリを待った時間 |

代わりにブラウザーのページからテストを実行することもできます。1件ずつ実行でき、実行の進捗と失敗の証拠がページに表示されます。`@quiesco/ui`をインストールして`npx quiesco ui --platform web`を起動してください（[テスト UI](https://docs.quiesco.dev/ja/ui.md)）。

## 次のステップ

* [同期](https://docs.quiesco.dev/ja/sync.md)：アイドルとは何か、終わらないアニメーションはどう扱うか。
* [APIリファレンス](https://docs.quiesco.dev/ja/api.md)：すべてのアクションとアサーション、そしてマッチャー（`within`、`has`、正規表現）。
* [Driverパターン](https://docs.quiesco.dev/ja/driver-pattern-cucumber.md)：テストスイートが大きくなったら、テストIDをテストの外に出す。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.