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

# Tiru API pihak ketiga dengan emulate

> Jalankan emulator lokal API pihak ketiga sebagai service e2e dan arahkan aplikasi Anda ke sana, bukan ke API sebenarnya.

[emulate](https://emulate.dev) menjalankan emulator lokal untuk API pihak
ketiga, termasuk Resend, GitHub, Stripe, Google, Twilio, Slack, dan provider
AI. Setiap emulator menyimpan state seperti API sebenarnya dan tidak
memerlukan akun atau akses jaringan. Jalankan emulator sebagai
[service](https://e2e.com/docs/id/services) sebelum aplikasi dimulai, lalu arahkan aplikasi ke sana,
bukan ke API sebenarnya.

## Instalasi

Instal emulate sebagai dependensi pengembangan:

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

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

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

## Mulai emulator

Mulai emulator dengan `createEmulator` di dalam service, lalu yield hal yang
dibutuhkan tes, seperti `url`-nya:

<Tabs dropdown label="Service">
  <Tab title="Resend">

Meniru pengiriman email, domain, API key, audiens, dan kontak, serta
menyimpan semua email yang dikirim di inbox.

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

Lihat dokumentasi emulate untuk [Resend](https://emulate.dev/docs/resend).

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

Meniru REST API (repositori, issue, pull request, Actions, pemeriksaan, dan
webhook), aplikasi OAuth, serta GitHub Apps. Seed menambahkan pengguna,
repositori, dan token untuk pengguna tersebut.

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

Lihat dokumentasi emulate untuk [GitHub](https://emulate.dev/docs/github).

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

Meniru pelanggan, metode pembayaran, payment intent, tagihan, produk, harga,
sesi Checkout dengan halaman ter-host, dan webhook bertanda tangan.

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

Lihat dokumentasi emulate untuk [Stripe](https://emulate.dev/docs/stripe).

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

Meniru proses masuk Google (OAuth 2.0 dan OpenID Connect) serta API Gmail,
Calendar, dan Drive. Seed menambahkan pengguna yang muncul di halaman masuk
emulator.

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

Lihat dokumentasi emulate untuk [Google](https://emulate.dev/docs/google).

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

Meniru Programmable Messaging, Verify, panggilan Voice, Conversations, dan
webhook bertanda tangan. Emulator menyediakan akun tes dan service Verify,
jadi tidak memerlukan seed; service akan memberikan kredensialnya.

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

Lihat dokumentasi emulate untuk [Twilio](https://emulate.dev/docs/twilio).

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

Meniru Web API, OAuth, webhook masuk, interaksi, dan callback Events API. Seed
menambahkan channel `#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();
  },
});
```

Lihat dokumentasi emulate untuk [Slack](https://emulate.dev/docs/slack).

  </Tab>
  <Tab title="Provider AI">

Meniru API OpenAI, Anthropic, dan Gemini serta Vercel AI Gateway. Balasan
berasal dari aturan, sehingga setiap eksekusi mendapat hasil yang sama. Seed
menambahkan satu aturan yang menjawab setiap permintaan.

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

Lihat dokumentasi emulate untuk [provider AI](https://emulate.dev/docs/ai).

  </Tab>
</Tabs>

Jangan yield seluruh objek emulator. Jika dilakukan, tes mana pun dapat
memanggil `close()` dan menghentikan emulator untuk semua worker.

## Konfigurasikan e2e

Tambahkan service di bawah `services` dalam konfigurasi, lalu teruskan URL
emulator ke aplikasi melalui fungsi `env`:

<Tabs follow label="Service">
  <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,
          }),
        },
      },
    },
  ],
});
```

Atur klien Resend aplikasi agar menggunakan `RESEND_BASE_URL`, bukan
`https://api.resend.com`. Kunci API apa pun dapat digunakan.

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

Atur klien GitHub aplikasi agar menggunakan `GITHUB_API_URL`, bukan
`https://api.github.com`, dan berikan token dari seed melalui `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,
          }),
        },
      },
    },
  ],
});
```

Atur klien Stripe aplikasi agar menggunakan `STRIPE_API_URL`, bukan
`https://api.stripe.com`. Kunci secret apa pun dapat digunakan.

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

Atur klien proses masuk aplikasi agar menggunakan `GOOGLE_ISSUER`, bukan
`https://accounts.google.com`. Klien menemukan endpoint di dokumen
`/.well-known/openid-configuration` milik emulator. Seed tidak menambahkan
klien OAuth, sehingga ID klien dan secret apa pun dapat digunakan.

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

Atur klien Twilio aplikasi agar menggunakan `TWILIO_API_URL`, bukan
`https://api.twilio.com`. Emulator menyediakan Verify di jalur `/verify`, jadi
kirim permintaan Verify ke `${TWILIO_API_URL}/verify`, bukan
`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`,
          }),
        },
      },
    },
  ],
});
```

Atur klien Slack aplikasi agar menggunakan `SLACK_API_URL`, bukan
`https://slack.com/api`. Token apa pun dapat digunakan. Emulator mencari
channel berdasarkan nama tanpa `#`, misalnya `feedback`, atau berdasarkan ID.

  </Tab>
  <Tab title="Provider 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`,
          }),
        },
      },
    },
  ],
});
```

SDK OpenAI membaca `OPENAI_BASE_URL` dan `OPENAI_API_KEY` secara otomatis.
Kunci API apa pun dapat digunakan.

  </Tab>
</Tabs>

Teruskan tipe konfigurasi ke `test.extend` agar fixture `services` memiliki
tipe yang sesuai di dalam tes:

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

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

## Tulis tes

<Tabs follow label="Service">
  <Tab title="Resend">

Daftar menggunakan alamat email unik, lalu periksa email sambutan melalui
Resend API milik emulator:

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

Laporkan bug, lalu periksa issue baru melalui GitHub API milik emulator:

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

Berlangganan menggunakan alamat email unik, lalu cari pelanggan melalui Stripe
API milik emulator:

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

Masuk sebagai pengguna dari seed di halaman masuk emulator, lalu periksa apakah
nama pengguna tersebut ditampilkan aplikasi:

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

Minta kode untuk nomor telepon, ambil kodenya dari emulator, lalu masukkan ke
aplikasi:

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

Kirim masukan, lalu periksa pesan di `#feedback` melalui Slack API milik
emulator:

```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="Provider AI">

Ringkas artikel, lalu periksa apakah halaman menampilkan balasan dari aturan
seed:

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

## Selanjutnya

<CardGroup cols={2}>
  <Card title="Service" icon="server" href="/services">
    Mulai dependensi aplikasi sebelum aplikasi berjalan, lalu gunakan di tes.
  </Card>
  <Card title="Referensi konfigurasi" icon="code" href="/reference/config#services">
    Key `services` dan fungsi `env`.
  </Card>
</CardGroup>
