> ## 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 模式

> 在测试和 App 之间放一个用业务语言写的 driver 类，让测试经得起 UI 变化。

测试应该写用户想做什么，而不是按了哪些按钮。把点击和 test id 放进自己写的 **driver**：一个用业务语言命名方法的类（`addTodo('Buy milk')`）。测试只调用 driver。UI 变了，只改 driver，测试不用动。

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

driver 在每种运行器里都一样，不同的只是测试怎么拿到它。示例使用[教程](https://docs.quiesco.dev/zh/tutorial.md)中的待办 App。

## Driver

一个接口描述测试需要什么，一个类通过 UI 来实现：

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

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

/** 待办测试需要的操作，用业务语言表达。 */
export interface TodoDriver {
  seed(todos: SeedTodo[]): Promise<void>;
  addTodo(title: string, notes?: string): Promise<void>;
  todoTitles(): Promise<string[]>;
}

/** 通过 UI、用 Quiesco 实现。只有这个类知道 test 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/zh/api.md#driver-thisapp)。
* driver 里优先用 Quiesco 的断言（`expectVisible`、`expectText`）：它们会重试，直到 App 显示出期望的状态。对查询结果做普通断言只检查一次；在操作之后这样做没问题，因为操作已经等 App 空闲了。

## 按平台区分的步骤

同一个步骤在不同平台上做法不同时，例如日期选择器在 iOS 上是内嵌的，在 Android 上是两个系统对话框，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);
  }
}
```

只针对一个平台的测试则加标签（`@ios`、`@android`、`@web`；见[标签](https://docs.quiesco.dev/zh/api-tags.md)）。

## 用同一批测试测 API

测试只看得到 `TodoDriver`，所以换一个实现，就能不经过 UI、直接对 App 的后端 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/zh/driver-pattern-cucumber.md#api-run)）。

## 选择测试运行器

> [card] [Vitest](https://docs.quiesco.dev/zh/driver-pattern-vitest.md)
>
> 把 driver 作为测试 fixture。

> [card] [Jest](https://docs.quiesco.dev/zh/driver-pattern-jest.md)
>
> 用 JavaScript 写 driver，在 `beforeEach` 里创建。

> [card] [Cucumber](https://docs.quiesco.dev/zh/driver-pattern-cucumber.md)
>
> 把 driver 放在 World 上，用业务语言写步骤。


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