> ## 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.

# Driverパターン

> テストとアプリのあいだにビジネスの言葉で書いたdriverクラスを置き、UIが変わってもテストが壊れないようにします。

テストには、どのボタンを押すかではなく、ユーザーが何をしたいかを書きます。タップやテストIDは、自分で書く**driver**、つまりビジネスの言葉でメソッドを名付けたクラス（`addTodo('Buy milk')`）に入れます。テストはdriverだけを呼びます。UIが変わったらdriverを直し、テストはそのままです。

```
test / step  →  TodoDriver (addTodo, todoTitles, …)  →  app (tap, type, query, …)
```

driverはどのテストランナーでも同じで、違うのはテストがdriverを受け取る方法だけです。例は[チュートリアル](https://docs.quiesco.dev/ja/tutorial.md)のToDoアプリを使います。

## Driver

テストに必要なことを表すインターフェースと、それをUI経由で行うクラスです。

```ts theme={null}
// e2e/todo-driver.ts
import type { Driver } from '@quiesco/core';

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

/** ToDoのテストに必要な操作を、ビジネスの言葉で表す。 */
export interface TodoDriver {
  seed(todos: SeedTodo[]): Promise<void>;
  addTodo(title: string, notes?: string): Promise<void>;
  todoTitles(): Promise<string[]>;
}

/** UI経由で、Quiescoを使って実装する。テストIDを知っているのはこのクラスだけ。 */
export class UiTodoDriver implements TodoDriver {
  private readonly app: Driver;

  constructor(app: Driver) {
    this.app = app;
  }

  async seed(todos: SeedTodo[]) {
    // UIを通さずにデータを用意する
    await this.app.backdoor('seedTodos', todos);
  }

  async addTodo(title: string, notes?: string) {
    await this.app.tap('add-todo');
    await this.app.type('title-input', title);
    if (notes !== undefined) await this.app.type('notes-input', notes);
    await this.app.tap('save-todo');
    await this.app.expectVisible('todo-list-screen');
  }

  async todoTitles() {
    return (await this.app.query('todo-title')).map((e) => e.text);
  }
}
```

* `app`は、テストランナーが各テストに渡す[Driver](https://docs.quiesco.dev/ja/api.md#driver-thisapp)です。
* driverの中ではQuiescoのアサーション（`expectVisible`、`expectText`）を優先してください。アプリが期待した状態になるまでリトライします。クエリ結果への普通のアサーションは1回しか確かめませんが、操作の直後なら問題ありません。操作がすでにアプリのアイドルを待っているからです。

## プラットフォームごとに異なるステップ

1つのステップのやり方がプラットフォームで違うとき、たとえば日付ピッカーがiOSではインライン、Androidでは2つのシステムダイアログのときは、driverが`this.app.platform`（`'ios' | 'android' | 'web'`）で分岐します。

```ts theme={null}
async setDueDate(date: Date) {
  if (this.app.platform === Platform.android) {
    await this.app.tap('pick-date');
    await this.app.setValue('due-date-picker', date);
    await this.app.tap('pick-time');
    await this.app.setValue('due-time-picker', date);
  } else {
    await this.app.setValue('due-picker', date);
  }
}
```

1つのプラットフォームだけのテストには、代わりにタグを付けます（`@ios`、`@android`、`@web`。[タグ](https://docs.quiesco.dev/ja/api-tags.md)を参照）。

## 同じテストをAPIに対して実行する

テストからは`TodoDriver`しか見えないので、別の実装を用意すれば、UIを通さずにアプリのバックエンドAPIに対して同じテストを数秒で実行できます。

```ts theme={null}
export class ApiTodoDriver implements TodoDriver {
  private readonly baseUrl: string;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  async seed(todos: SeedTodo[]) {
    await fetch(`${this.baseUrl}/todos`, { method: 'PUT', body: JSON.stringify(todos) });
  }

  async addTodo(title: string, notes?: string) {
    await fetch(`${this.baseUrl}/todos`, { method: 'POST', body: JSON.stringify({ title, notes }) });
  }

  async todoTitles() {
    const res = await fetch(`${this.baseUrl}/todos`);
    return ((await res.json()) as { title: string }[]).map((t) => t.title);
  }
}
```

driverは環境変数で選びます。Cucumberなら、APIでの実行ではQuiescoをまったく使わずに済みます（[APIでの実行](https://docs.quiesco.dev/ja/driver-pattern-cucumber.md#api-run)）。

## テストランナーを選ぶ

> [card] [Vitest](https://docs.quiesco.dev/ja/driver-pattern-vitest.md)
>
> driverをテストのフィクスチャーにする。

> [card] [Jest](https://docs.quiesco.dev/ja/driver-pattern-jest.md)
>
> driverをJavaScriptで書き、`beforeEach`で作る。

> [card] [Cucumber](https://docs.quiesco.dev/ja/driver-pattern-cucumber.md)
>
> driverをWorldに置き、ステップをビジネスの言葉で書く。


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