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

# 使用 emulate 模拟第三方 API

> 将第三方 API 的本地模拟器作为 e2e 服务运行，并将你的应用指向它而非真实 API。

[emulate](https://emulate.dev) 为第三方 API 运行本地模拟器，包括 Resend、GitHub、Stripe、Google、Twilio、Slack 和 AI 提供方。每个模拟器都会像真实 API 一样维护状态，且无需账号或网络连接。先将模拟器作为[服务](https://e2e.com/docs/zh/services)在应用之前启动，再让应用指向该模拟器而非真实 API。

## 安装

将 emulate 安装为开发依赖项：

<CodeGroup>
```bash npm
npm install --save-dev emulate
```

```bash pnpm
pnpm add -D emulate
```

```bash bun
bun add -d emulate
```
</CodeGroup>

## 启动模拟器

在服务中使用 `createEmulator` 启动模拟器，并 yield 测试所需的信息（例如其 `url`）：

<Tabs dropdown label="服务">
  <Tab title="Resend">

模拟发送邮件、域名、API 密钥、受众群体和联系人，并保留所有已发送邮件的收件箱。

```ts title="services/resend.ts"

export const resend = defineService({
  async *start() {
    const emulator = await createEmulator({ service: 'resend', port: 0 });

    yield { url: emulator.url };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [Resend](https://emulate.dev/docs/resend)。

  </Tab>
  <Tab title="GitHub">

模拟 REST API（仓库、议题、拉取请求、Actions、检查和 Webhook）、OAuth 应用以及 GitHub Apps。种子数据会添加一个用户、一个仓库以及该用户的令牌。

```ts title="services/github.ts"

export const github = defineService({
  async *start() {
    const emulator = await createEmulator({
      service: 'github',
      port: 0,
      seed: {
        tokens: { gh_test: { login: 'octocat', scopes: ['repo'] } },
        github: {
          users: [{ login: 'octocat' }],
          repos: [{ owner: 'octocat', name: 'hello-world' }],
        },
      },
    });

    yield { url: emulator.url, token: 'gh_test' };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [GitHub](https://emulate.dev/docs/github)。

  </Tab>
  <Tab title="Stripe">

模拟客户、支付方式、支付意图、扣款、商品、价格、带托管页面的 Checkout 会话以及签名 Webhook。

```ts title="services/stripe.ts"

export const stripe = defineService({
  async *start() {
    const emulator = await createEmulator({ service: 'stripe', port: 0 });

    yield { url: emulator.url };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [Stripe](https://emulate.dev/docs/stripe)。

  </Tab>
  <Tab title="Google">

模拟 Google 登录（OAuth 2.0 和 OpenID Connect）以及 Gmail、Calendar 和 Drive API。种子数据会添加一个用户，该用户会显示在模拟器的登录页面上。

```ts title="services/google.ts"

export const google = defineService({
  async *start() {
    const emulator = await createEmulator({
      service: 'google',
      port: 0,
      seed: { google: { users: [{ email: 'ada@example.com', name: 'Ada Lovelace' }] } },
    });

    yield { url: emulator.url };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [Google](https://emulate.dev/docs/google)。

  </Tab>
  <Tab title="Twilio">

模拟 Programmable Messaging、Verify、语音通话、Conversations 以及签名 Webhook。它内置了一个测试账号和一个 Verify 服务，因此无需种子数据，服务直接 yield 它们的凭据即可。

```ts title="services/twilio.ts"

export const twilio = defineService({
  async *start() {
    const emulator = await createEmulator({ service: 'twilio', port: 0 });

    yield {
      url: emulator.url,
      accountSid: 'AC00000000000000000000000000000000',
      authToken: 'twilio_test_auth_token',
      verifyServiceSid: 'VA00000000000000000000000000000000',
    };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [Twilio](https://emulate.dev/docs/twilio)。

  </Tab>
  <Tab title="Slack">

模拟 Web API、OAuth、传入 Webhook、交互组件以及 Events API 回调。种子数据会添加一个 `#feedback` 频道。

```ts title="services/slack.ts"

export const slack = defineService({
  async *start() {
    const emulator = await createEmulator({
      service: 'slack',
      port: 0,
      seed: { slack: { channels: [{ name: 'feedback' }] } },
    });

    yield { url: emulator.url };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [Slack](https://emulate.dev/docs/slack)。

  </Tab>
  <Tab title="AI 提供方">

模拟 OpenAI、Anthropic 和 Gemini API 以及 Vercel AI Gateway。响应由规则生成，因此每次运行都会得到相同的输出。种子数据添加了一条回复所有请求的规则。

```ts title="services/ai.ts"

export const ai = defineService({
  async *start() {
    const emulator = await createEmulator({
      service: 'ai',
      port: 0,
      seed: {
        ai: {
          rules: [{ id: 'summary', reply: [{ type: 'text', text: 'A short summary of the article.' }] }],
        },
      },
    });

    yield { url: emulator.url };

    await emulator.close();
  },
});
```

详见 emulate 文档中的 [AI providers](https://emulate.dev/docs/ai)。

  </Tab>
</Tabs>

不要将整个 emulator 对象 yield 出去，否则任意测试都可以调用它的 `close()`，从而为所有工作进程停止该模拟器。

## 配置 e2e

在配置的 `services` 中添加该服务，然后通过 `env` 函数将模拟器的 URL 传递给你的应用：

<Tabs follow label="服务">
  <Tab title="Resend">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.signup',
  services: { resend },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            RESEND_API_KEY: 're_test',
            RESEND_BASE_URL: services.resend.url,
          }),
        },
      },
    },
  ],
});
```

将应用的 Resend 客户端指向 `RESEND_BASE_URL` 而非 `https://api.resend.com`。任意 API 密钥均可使用。

  </Tab>
  <Tab title="GitHub">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.bugs',
  services: { github },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            GITHUB_TOKEN: services.github.token,
            GITHUB_API_URL: services.github.url,
          }),
        },
      },
    },
  ],
});
```

将应用的 GitHub 客户端指向 `GITHUB_API_URL` 而非 `https://api.github.com`，并为其提供来自 `GITHUB_TOKEN` 的种子令牌。

  </Tab>
  <Tab title="Stripe">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.billing',
  services: { stripe },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            STRIPE_SECRET_KEY: 'sk_test_123',
            STRIPE_API_URL: services.stripe.url,
          }),
        },
      },
    },
  ],
});
```

将应用的 Stripe 客户端指向 `STRIPE_API_URL` 而非 `https://api.stripe.com`。任意密钥均可使用。

  </Tab>
  <Tab title="Google">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.accounts',
  services: { google },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            GOOGLE_CLIENT_ID: 'test-client-id',
            GOOGLE_CLIENT_SECRET: 'test-client-secret',
            GOOGLE_ISSUER: services.google.url,
          }),
        },
      },
    },
  ],
});
```

将应用的登录客户端指向 `GOOGLE_ISSUER` 而非 `https://accounts.google.com`。客户端会从模拟器的 `/.well-known/openid-configuration` 文档中发现各个端点。种子数据未添加任何 OAuth 客户端，因此任意客户端 ID 和密钥均可使用。

  </Tab>
  <Tab title="Twilio">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.phone',
  services: { twilio },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            TWILIO_ACCOUNT_SID: services.twilio.accountSid,
            TWILIO_AUTH_TOKEN: services.twilio.authToken,
            TWILIO_VERIFY_SERVICE_SID: services.twilio.verifyServiceSid,
            TWILIO_API_URL: services.twilio.url,
          }),
        },
      },
    },
  ],
});
```

将应用的 Twilio 客户端指向 `TWILIO_API_URL` 而非 `https://api.twilio.com`。模拟器在 `/verify` 路径下提供 Verify 服务，因此请将 Verify 请求发送到 `${TWILIO_API_URL}/verify` 而非 `https://verify.twilio.com`。

  </Tab>
  <Tab title="Slack">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.feedback',
  services: { slack },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            SLACK_BOT_TOKEN: 'xoxb-test',
            SLACK_API_URL: `${services.slack.url}/api`,
          }),
        },
      },
    },
  ],
});
```

将应用的 Slack 客户端指向 `SLACK_API_URL` 而非 `https://slack.com/api`。任意令牌均可使用。模拟器支持通过不带 `#` 的频道名称（例如 `feedback`）或频道 ID 查找频道。

  </Tab>
  <Tab title="AI 提供方">

```ts title="e2e.config.ts"

export default defineConfig({
  projectId: 'dev.example.summaries',
  services: { ai },
  targets: [
    {
      name: 'web',
      engine: web(),
      app: {
        url: 'http://127.0.0.1:0',
        command: {
          executable: 'node',
          args: ['app/server.mjs'],
          env: ({ services }) => ({
            PORT: '{port}',
            OPENAI_API_KEY: 'test',
            OPENAI_BASE_URL: `${services.ai.url}/v1`,
          }),
        },
      },
    },
  ],
});
```

OpenAI SDK 会自动读取 `OPENAI_BASE_URL` 和 `OPENAI_API_KEY`。任意 API 密钥均可使用。

  </Tab>
</Tabs>

将配置的类型传入 `test.extend`，以便在测试中为 `services` 测试夹具提供类型推导：

```ts title="tests/fixtures.ts"

export const test = base.extend<{}, {}, typeof config>({});
```

## 编写测试

<Tabs follow label="服务">
  <Tab title="Resend">

使用唯一的邮箱地址注册，然后在模拟器的 Resend API 中检查欢迎邮件：

```ts title="tests/signup.e2e.ts"

test('signing up sends a welcome email through Resend', async ({ app, screen, services }) => {
  const address = `ada+${randomUUID()}@example.com`;

  await app.open('/');
  await screen.getByRole('textbox', { name: 'Email' }).fill(address);
  await screen.getByRole('button', { name: 'Sign up' }).click();
  await expect(screen.getByRole('heading', { name: 'Check your inbox' })).toBeVisible();

  const response = await fetch(`${services.resend.url}/emails`);
  const { data } = await response.json();

  expect(data.filter((email: { to: string[] }) => email.to.includes(address))).toEqual([
    expect.objectContaining({ to: [address], subject: 'Welcome' }),
  ]);
});
```

  </Tab>
  <Tab title="GitHub">

提交一个错误报告，然后在模拟器的 GitHub API 中检查新创建的议题：

```ts title="tests/report-bug.e2e.ts"

test('reporting a bug opens a GitHub issue', async ({ app, screen, services }) => {
  const title = `Checkout fails ${randomUUID()}`;

  await app.open('/');
  await screen.getByRole('textbox', { name: 'Title' }).fill(title);
  await screen.getByRole('button', { name: 'Report bug' }).click();
  await expect(screen.getByRole('heading', { name: 'Thanks for the report' })).toBeVisible();

  const response = await fetch(`${services.github.url}/repos/octocat/hello-world/issues`, {
    headers: { authorization: `Bearer ${services.github.token}` },
  });

  const issues = await response.json();

  expect(issues.map((issue: { title: string }) => issue.title)).toContain(title);
});
```

  </Tab>
  <Tab title="Stripe">

使用唯一的邮箱地址订阅，然后在模拟器的 Stripe API 中查询该客户：

```ts title="tests/subscribe.e2e.ts"

test('subscribing creates a Stripe customer', async ({ app, screen, services }) => {
  const email = `ada+${randomUUID()}@example.com`;

  await app.open('/');
  await screen.getByRole('textbox', { name: 'Email' }).fill(email);
  await screen.getByRole('button', { name: 'Subscribe' }).click();
  await expect(screen.getByRole('heading', { name: 'You are subscribed' })).toBeVisible();

  const response = await fetch(`${services.stripe.url}/v1/customers?email=${encodeURIComponent(email)}`, {
    headers: { authorization: 'Bearer sk_test_123' },
  });
  const { data } = await response.json();

  expect(data).toEqual([expect.objectContaining({ email })]);
});
```

  </Tab>
  <Tab title="Google">

在模拟器的登录页面上以种子用户身份登录，然后检查应用是否显示该用户的姓名：

```ts title="tests/sign-in.e2e.ts"

test('signing in with Google shows the account name', async ({ app, screen }) => {
  await app.open('/');
  await screen.getByRole('link', { name: 'Sign in with Google' }).click();
  await screen.getByRole('button', { name: /ada@example\.com/ }).click();

  await expect(screen.getByRole('heading', { name: 'Signed in as Ada Lovelace' })).toBeVisible();
});
```

  </Tab>
  <Tab title="Twilio">

为手机号请求验证码，从模拟器读取该验证码，再将其输入应用：

```ts title="tests/verify-phone.e2e.ts"

test('verifying a phone number checks the code Twilio sent', async ({ app, screen, services }) => {
  const phone = '+15550002222';

  await app.open('/');
  await screen.getByRole('textbox', { name: 'Phone number' }).fill(phone);
  await screen.getByRole('button', { name: 'Send code' }).click();
  await expect(screen.getByRole('textbox', { name: 'Code' })).toBeVisible();

  const { url, accountSid, authToken } = services.twilio;
  const response = await fetch(`${url}/_twilio/simulate/verification-code?To=${encodeURIComponent(phone)}`, {
    headers: { authorization: `Basic ${btoa(`${accountSid}:${authToken}`)}` },
  });
  const { code } = await response.json();

  await screen.getByRole('textbox', { name: 'Code' }).fill(code);
  await screen.getByRole('button', { name: 'Verify' }).click();
  await expect(screen.getByRole('heading', { name: 'Phone verified' })).toBeVisible();
});
```

  </Tab>
  <Tab title="Slack">

发送反馈，然后在模拟器的 Slack API 中检查 `#feedback` 频道里的消息：

```ts title="tests/send-feedback.e2e.ts"

test('sending feedback posts it to #feedback', async ({ app, screen, services }) => {
  const feedback = `The new search is great ${randomUUID()}`;

  await app.open('/');
  await screen.getByRole('textbox', { name: 'Feedback' }).fill(feedback);
  await screen.getByRole('button', { name: 'Send' }).click();
  await expect(screen.getByRole('heading', { name: 'Thanks for your feedback' })).toBeVisible();

  const slack = async (method: string, body: object = {}) => {
    const response = await fetch(`${services.slack.url}/api/${method}`, {
      method: 'POST',
      headers: { authorization: 'Bearer xoxb-test', 'content-type': 'application/json' },
      body: JSON.stringify(body),
    });

    return response.json();
  };

  const { channels } = await slack('conversations.list');
  const channel = channels.find((entry: { name: string }) => entry.name === 'feedback');
  const { messages } = await slack('conversations.history', { channel: channel.id });

  expect(messages.map((message: { text: string }) => message.text)).toContain(feedback);
});
```

  </Tab>
  <Tab title="AI 提供方">

对文章生成摘要，然后检查页面是否显示种子规则配置的回复：

```ts title="tests/summarize.e2e.ts"

test("summarizing an article shows the model's reply", async ({ app, screen }) => {
  await app.open('/');
  await screen.getByRole('textbox', { name: 'Article' }).fill('A long article about local testing.');
  await screen.getByRole('button', { name: 'Summarize' }).click();

  await expect(screen.getByText('A short summary of the article.')).toBeVisible();
});
```

  </Tab>
</Tabs>

## 下一步

<CardGroup cols={2}>
  <Card title="服务" icon="server" href="/services">
    在应用运行前启动其依赖项，并在测试中使用它们。
  </Card>
  <Card title="配置参考" icon="code" href="/reference/config#services">
    `services` 配置项和 `env` 函数。
  </Card>
</CardGroup>
