> ## 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) は、Resend、GitHub、Stripe、Google、Twilio、Slack、AI プロバイダーなどのサードパーティ API 向けローカルエミュレーターを実行します。各エミュレーターは実際の API と同様に状態を保持し、アカウントやネットワーク接続なしで動作します。アプリを起動する前にエミュレーターを
[サービス](https://e2e.com/docs/ja/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` を使ってエミュレーターを起動し、`url` などテストに必要な値だけを `yield` します。

<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（リポジトリ、Issue、プルリクエスト、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">

顧客、支払い方法、PaymentIntent、課金、商品、価格、ホストページ付きの 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、Incoming 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 をエミュレートします。応答はルールに基づいて返されるため、毎回同じ出力が得られます。シードデータですべてのリクエストに応答するルールを 1 件追加します。

```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>

エミュレーターオブジェクト全体は `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 クライアントの接続先を `https://api.resend.com` ではなく `RESEND_BASE_URL` に向けます。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 クライアントの接続先を `https://api.github.com` ではなく `GITHUB_API_URL` に向け、シードで作成したトークンを `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 クライアントの接続先を `https://api.stripe.com` ではなく `STRIPE_API_URL` に向けます。シークレットキーは任意の値で動作します。

  </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,
          }),
        },
      },
    },
  ],
});
```

アプリのサインインクライアントの接続先を `https://accounts.google.com` ではなく `GOOGLE_ISSUER` に向けます。エンドポイントはエミュレーターの `/.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 クライアントの接続先を `https://api.twilio.com` ではなく `TWILIO_API_URL` に向けます。エミュレーターは Verify を `/verify` 配下で提供するため、Verify リクエストは `https://verify.twilio.com` ではなく `${TWILIO_API_URL}/verify` へ送信してください。

  </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 クライアントの接続先を `https://slack.com/api` ではなく `SLACK_API_URL` に向けます。トークンは任意の値で動作します。エミュレーターは `#` を除いたチャンネル名（`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>

テスト内で `services` フィクスチャに型が付くよう、設定の型を `test.extend` に渡します。

```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 で新しい Issue が作成されたことを確認します。

```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>
