---
url: https://game-engine-io.github.io/enginex-frontend-sdk/guide/testing.md
---
# Testing and mocks

`@getenginex/sdk/testing` provides `createMockFetch`: a mock `fetch` to pass to
`createEnginexClient({ fetch })`, with no new dependency (no MSW). The default responses
match the SDK's real schemas — even with `validation: 'strict'` — so you can write
tests (or a demo, or a Storybook) without standing up the gateway.

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { createMockFetch } from '@getenginex/sdk/testing'

const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test', // in Node (Vitest, Jest): absolute baseUrl + tenantHost
  tenantHost: 'casino.test', // in the browser, both are optional
  fetch: createMockFetch(),
})

const config = await enginex.config.get()
const result = await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })
// result.status === 'authenticated'
```

In Node (Vitest, Jest, scripts) there is no `location`: without an absolute `baseUrl` and `tenantHost`, the
first request rejects with `CONFIGURATION_ERROR` — even with the mock, which responds to any
origin. The values can be fictitious (`https://gateway.test`, `casino.test`); in the browser (demo,
Storybook) they are optional. See [Tenant and domains](/concepts/tenant).

## Default routes

With no options, `createMockFetch()` responds to:

* `GET /api/v1/config`, `/api/v1/config/branding`, `/api/v1/config/products`,
  `/api/v1/config/sportsbook` and `/api/v1/support/config`,
  with plausible data for a fictitious operator;
* `POST /api/v1/auth/register`, which returns a new `userId` without authenticating;
* `POST /api/v1/auth/login`, which authenticates and stores simulated session tokens;
* `POST /api/v1/auth/refresh`, which always returns new tokens — the session's automatic refresh
  (proactive or after a 401) works end to end against the mock, with no need to simulate it
  by hand;
* `POST /api/v1/auth/logout`, which always responds with success;
* `GET`/`PUT /api/v1/me`, `GET /api/v1/me/sessions` and `DELETE /api/v1/me/sessions/current` and
  `/mock-session-2` (in-memory profile);
* wallet: `GET /api/v1/wallet`, `/wallet/balance` and `/wallet/transactions` (initial balance of
  R$ 1,500.00 and a short statement, filterable by `category`);
* deposit: `POST /api/v1/deposits/pix`, `GET /api/v1/deposits/:depositId` and `GET /api/v1/deposits`
  (the charge stays `pending`);
* withdrawal: `POST /api/v1/withdrawals`, `POST /api/v1/withdrawals/confirm-otp`,
  `GET /api/v1/withdrawals/:withdrawalId`, `GET /api/v1/withdrawals` and
  `DELETE /api/v1/withdrawals/:withdrawalId` — the withdrawal debits the balance (and cancellation refunds it), and
  an amount above the balance responds `INSUFFICIENT_BALANCE`;
* PIX keys: `POST`/`GET /api/v1/pix-keys`, `DELETE /api/v1/pix-keys/:keyId` and
  `PUT /api/v1/pix-keys/:keyId/default` (starts with a default CPF key);
* KYC: `GET /api/v1/kyc/status` (level `basic`, `not_started`) and the multipart upload of
  `POST /api/v1/kyc/documents` (201; 400 `INVALID_ARGUMENT` with no file or with an invalid type, as
  in the gateway), which moves the status to `pending`;
* notifications: `GET /api/v1/notifications` (two samples, one unread; `page`, `limit`, `unread=true`),
  `PUT /api/v1/notifications/:notificationId/read` and `GET`/`PUT /api/v1/notifications/preferences`.

State is per mock (each `createMockFetch()` starts from scratch). As in the gateway, deposit and withdrawal
require `Idempotency-Key` (the SDK always sends it) and the same key replays the first response; the
minimum/maximum limits come from `GET /config`. Unlike today's gateway, `GET /withdrawals` lists the withdrawals
made in the mock.

A created deposit stays `pending` until the "bank" confirms the PIX. To simulate the payment, keep the
mock's `fetch` and call `markDepositPaid`: the deposit becomes `completed` and the balance goes up by its amount
(only once).

```ts
import { createMockFetch, markDepositPaid } from '@getenginex/sdk/testing'

const mockFetch = createMockFetch()
// ... createEnginexClient({ ..., fetch: mockFetch }), login and createPix
markDepositPaid(mockFetch, pix.id)
await enginex.deposits.get({ depositId: pix.id }) // status: 'completed'
```

These are also the formats of the `options.routes` keys: method + **full** path, with the
`/api/v1` prefix (e.g. `'POST /api/v1/auth/login'`, never `'POST /auth/login'`). A `:name` segment
matches any value, which the handler receives in `req.params?.name` (the mock always fills in
`params`; in the type it is optional).

Which handler responds, in order:

1. **Exact route**: the one in `options.routes` if there is one, otherwise the default. A default exact route wins
   even over a parameterized route of yours — e.g. `'GET /api/v1/wallet/:x'` does not intercept
   `/api/v1/wallet/balance`; to override an exact default route, use the same exact key.
2. **Parameterized route**: those in `options.routes` first, then the defaults — e.g.
   your `'GET /api/v1/deposits/:id'` wins over the default `'GET /api/v1/deposits/:depositId'`.
3. None: `404 NOT_FOUND`.

A route called without a handler (default or from `options.routes`) returns `404 NOT_FOUND`, instead of
throwing — the error reaches the caller as a normal `EnginexError`.

## 2FA scenario

```ts
const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test',
  tenantHost: 'casino.test',
  fetch: createMockFetch({ twoFactorRequired: true }),
})

let result = await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })
// result.status === '2fa_required'

result = await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123', twoFactorCode: '123456' })
// result.status === 'authenticated'
```

## Withdrawal with OTP

By default the mock simulates an operator with no OTP on withdrawals (`withdrawals.request` already returns
`{ status: 'created' }`). With `withdrawalOtp: true`, `GET /config` starts advertising the
`withdraw_money` flow, `request` returns `{ status: 'otp_required' }` and `confirmOtp` with any non-empty
code submits the withdrawal:

```ts
const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test',
  tenantHost: 'casino.test',
  fetch: createMockFetch({ withdrawalOtp: true }),
})

await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })
const result = await enginex.withdrawals.request({ amount: 5_000, pixKeyType: 'cpf' })
// result.status === 'otp_required'
const withdrawal = await enginex.withdrawals.confirmOtp({ otp: '123456' })
// withdrawal.status === 'pending'
```

Like the gateway, the request stays pending for 10 minutes (also after `confirmOtp`): repeating it with
the same `Idempotency-Key` and body returns the same response, and any other `request` is refused with
`FAILED_PRECONDITION` (422) `another withdrawal request is pending`.

## Overriding routes and simulating errors

`options.routes` overrides a default handler or adds a new route, keyed by
`"METHOD /api/v1/path"`. Use the `ok` and `fail` helpers to build responses in the same format
as the gateway:

```ts
import { createMockFetch, fail, ok } from '@getenginex/sdk/testing'
import { isEnginexError } from '@getenginex/sdk'

const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test',
  tenantHost: 'casino.test',
  fetch: createMockFetch({
    routes: {
      'POST /api/v1/auth/login': () => fail(401, 'INVALID_CREDENTIALS', 'wrong password'),
      'GET /api/v1/config/products': () => ok({ products: [] }),
      'GET /api/v1/deposits/:depositId': (req) => fail(404, 'NOT_FOUND', `no ${req.params?.depositId}`),
    },
  }),
})

try {
  await enginex.auth.login({ email: 'ana@exemplo.com', password: 'wrong' })
} catch (e) {
  if (isEnginexError(e, 'INVALID_CREDENTIALS')) {
    // ...
  }
}
```

`ok(data, meta?, status?)` builds `{ success: true, data, meta? }` (status `200`, or the one given — e.g.
`201` to imitate creation routes); `fail(status, code, message?, details?)`
builds `{ success: false, error: { code, message, details? } }` with the given HTTP status — the
same format `errorFromHttp` expects in order to become an `EnginexError` (see [Errors](/concepts/errors)).

## Simulated identity

`options.user` replaces the `userId`/`operatorId` used in the simulated access token's claims and in
the `auth` responses (default: `mock-user-1` / `mock-operator-1`):

```ts
createMockFetch({ user: { userId: 'u-42', operatorId: 'op-casino' } })
```

## Realtime

`createMockRealtime()` is the equivalent for [realtime](/concepts/realtime): a fake `WebSocket`
for `createEnginexClient({ webSocket })`, with no dependencies. It replies `ack` to each `subscribe` and
`pong` to each ping, and opens the connection asynchronously (one microtask: await before emitting).

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { coreTopics, createRealtime } from '@getenginex/sdk/realtime'
import { createMockFetch, createMockRealtime } from '@getenginex/sdk/testing'

const mock = createMockRealtime()
const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test',
  tenantHost: 'casino.test',
  fetch: createMockFetch(),
  webSocket: mock.webSocket,
})
await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })

createRealtime(enginex).subscribe(coreTopics.balance(), (update) => console.log(update.available))
await Promise.resolve() // the connection opens
mock.emit('balance:mock-user-1', 'balance_update', {
  available: 5_000,
  change: 5_000,
  change_type: 'credit',
  updated_at: new Date().toISOString(),
})
```

| Control                                           | What it does                                                                                   |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `connections()`                                   | Connections opened so far (the `url` includes the token, for asserts).                         |
| `emit(topic, type, payload)`                      | Simple message (multi-tenant mode); the payload goes as on the wire, in `snake_case`.          |
| `emitSequenced(topic, kind, seq, payload?)`       | `snapshot`, `delta` or `heartbeat` with the sequenced-mode envelope (a gap produces `snapshot_request`). |
| `drop(code?)`                                     | Drops the connection (default 1006): the client reconnects and triggers `onResync`.            |
| `rejectPrivate(topic?)`                           | Replies `error unauthorized` to private `subscribe`s (those already sent and new ones): one extra attempt and then `closed`. |
| `acceptPrivate(topic?)`                           | Undoes `rejectPrivate`: the next `subscribe`s get `ack` again (the blocked client reconnects with a new token). |
| `sent()`                                          | Frames sent by the client (`{ type, topic? }`).                                                |

For `rejectPrivate()` with no argument, a topic is **private** if it ends in the user (`sub`) of the
connection's token (`balance:<sub>`, `predictions:orders:<sub>`...), with no list of prefixes. If a public
topic in your test could have an id equal to the user's, pass your own criterion:
`createMockRealtime({ isPrivate: (topic) => topic.startsWith('balance:') })`.

## Product packages and adapters {#product-packages-and-adapters}

The product packages bring their mock routes in their own `/testing` entry: `withIgamingRoutes`
(`@getenginex/sdk-igaming/testing`) and `withPredictionsRoutes` (`@getenginex/sdk-predictions/testing`) take
the options of `createMockFetch` and add their routes to the core ones. They compose, and the routes you pass
win over the defaults:

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { createMockFetch, fail } from '@getenginex/sdk/testing'
import { createIgaming } from '@getenginex/sdk-igaming'
import { withIgamingRoutes } from '@getenginex/sdk-igaming/testing'
import { createPredictions } from '@getenginex/sdk-predictions'
import { withPredictionsRoutes } from '@getenginex/sdk-predictions/testing'

const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test',
  tenantHost: 'casino.test',
  // core + iGaming + Predictions routes; your `routes` still win over all of them
  fetch: createMockFetch(
    withIgamingRoutes(
      withPredictionsRoutes({
        routes: { 'GET /api/v1/games/:gameId': () => fail(404, 'GAME_NOT_FOUND') },
      }),
    ),
  ),
})
const igaming = createIgaming(enginex)
const predictions = createPredictions(enginex)
```

What each product mock answers (catalog, bonuses, orders, portfolio...) is on the product page:
[iGaming](/igaming/#tests) and [Predictions](/predictions/). To test components, the adapters use these same
mocks with the testing library of each framework: [React](/frameworks/react#testing),
[Next.js](/frameworks/next#testing) and [Vue](/frameworks/vue#testing).

## Full example

The `examples/vanilla-vite` project of the repository sets up a client with `createMockFetch`, loads the config
and does a mocked login, with no gateway at all. How to run it, and the Next.js and Vue examples, in
[Examples](/guide/installation#examples).
