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

# Client & connection

> Create a TestDriver client, connect it to a sandbox, and disconnect when you're done.

Every test talks to its sandbox through a TestDriver client. There are two ways to create one:

* **`TestDriver(context)`** from `testdriverai/vitest/hooks`. Use this in Vitest tests. It connects and disconnects for you.
* **`new TestDriver()`** from `testdriverai`. Use this outside Vitest's per-test hooks, when you manage the connection yourself.

```javascript theme={null}
import { TestDriver } from 'testdriverai/vitest/hooks';

test('opens the login page', async (context) => {
  const testdriver = TestDriver(context);
  await testdriver.provision.chrome({ url: 'https://testdriver-sandbox.vercel.app/login' });
});
```

## TestDriver(context, options)

Creates a client for the current Vitest test.

```typescript theme={null}
TestDriver(context: TestContext, options?: TestDriverOptions): TestDriver
```

### Parameters

**context** `TestContext` *required*

The context Vitest passes to your test function, as in `async (context) => { ... }`. TestDriver throws if it's missing.

**options** `TestDriverOptions`

Client options, such as `os`, `preview`, `cache`, or `keepAlive`. See [Options](https://docs.testdriver.ai/options.md) for the full list.

**hook-only options**

**apiKey** `string`

Your TestDriver API key. Defaults to the `TD_API_KEY` environment variable, which TestDriver also loads from `.env`.

**debugOnFailure** `boolean` (default: false)

If the test fails, keep its sandbox running instead of disconnecting, and print the sandbox id so you can reconnect to it.

### What it does

* **Connects automatically.** It authenticates and connects to a sandbox in the background. Your first command waits for the connection.
* **Disconnects automatically** when the test finishes.
* **Returns one client per test.** Calling it again in the same test returns the same client. A retried test gets a new one.
* **Reads `TD_OS`.** If you don't pass `os`, it uses the `TD_OS` environment variable, then Linux.

### Returns

A connected `TestDriver` client.

## new TestDriver(apiKey, options)

Creates a client that you connect and disconnect yourself.

```typescript theme={null}
new TestDriver(apiKey?: string, options?: TestDriverOptions)
new TestDriver(options?: TestDriverOptions)
```

### Parameters

**apiKey** `string`

Your TestDriver API key. Defaults to `TD_API_KEY`, which TestDriver loads from `.env`. Create one at [console.testdriver.ai/team/api-keys](https://console.testdriver.ai/team/api-keys).

**options** `TestDriverOptions`

Client options. See [Options](https://docs.testdriver.ai/options.md).

### Example

Share one sandbox across a test file by connecting in `beforeAll`:

```javascript tests/dashboard.test.mjs theme={null}
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import TestDriver from 'testdriverai';

describe('Dashboard', () => {
  let testdriver;

  beforeAll(async () => {
    testdriver = new TestDriver({ os: 'linux' });
    await testdriver.connect();
    await testdriver.provision.chrome({ url: 'https://testdriver-sandbox.vercel.app/login' });
  });

  afterAll(async () => {
    await testdriver.disconnect();
  });

  it('shows the login form', async () => {
    const result = await testdriver.assert('a login form is visible');
    expect(result).toBe(true);
  });
});
```

## connect(options)

Connects the client to a sandbox. By default, it creates a new sandbox.

```typescript theme={null}
testdriver.connect(options?: ConnectOptions): Promise<SandboxInstance>
```

`connect()` authenticates first if needed. You don't need to call `auth()` yourself.

### Parameters

**options** `ConnectOptions`

**properties**

**sandboxId** `string`

Reconnect to this existing sandbox instead of creating one.

**requireSandbox** `boolean` (default: false)

With `sandboxId`, throw if that sandbox is gone, instead of creating a new, empty one in its place.

**reconnect** `boolean`

Reconnect to the last sandbox this project used, recorded in `.testdriver/last-sandbox`. Provision calls are skipped, because the app is already running. Throws if there's no previous sandbox.

**newSandbox** `boolean` (default: true)

Create a new sandbox. Set to `false` when you pass `sandboxId` or `reconnect`.

**keepAlive** `number` (default: 60000)

Milliseconds to keep the sandbox running after `disconnect()`, so you can reconnect. Capped at 30 minutes. `0` uses the default.

**os** `string` (default: linux)

`"linux"` or `"windows"`. [Enterprise](https://testdriver.ai/enterprise/) Windows is available on Enterprise plans.

**preview** `string` (default: browser)

Where to show the live run: `"browser"`, `"ide"` (needs the TestDriver extension), or `"none"`.

**reuseConnection** `boolean` (default: true)

Reuse a recent connection if one is available.

**ip** `string`

Connect directly to a running sandbox at this IP address, for self-hosted machines. [Enterprise](https://testdriver.ai/enterprise/)

**sandboxAmi** `string`

Custom AMI ID for the sandbox, for self-hosted AWS deployments. [Enterprise](https://testdriver.ai/enterprise/)

**sandboxInstance** `string`

EC2 instance type for the sandbox, for self-hosted AWS deployments. [Enterprise](https://testdriver.ai/enterprise/)

**e2bTemplateId** `string`

E2B template ID to create the sandbox from.

**headless** `boolean` (default: false)

Deprecated. Use `preview: "none"` instead.

### Returns

**SandboxInstance** `object`

**properties**

**instanceId** `string`

The sandbox's ID.

**ip** `string`

The sandbox's IP address.

**vncPort** `number`

The port for the sandbox's remote display.

### Errors

Throws `Already connected` if the client is already connected. Create a new client to connect again.

### Example

```javascript theme={null}
const testdriver = new TestDriver();

// Reattach to a sandbox you kept alive earlier
const sandbox = await testdriver.connect({ sandboxId: 'sandbox-abc123', newSandbox: false });
console.log(sandbox.instanceId);
```

## disconnect()

Disconnects from the sandbox. The sandbox keeps running for the `keepAlive` time, then shuts down.

```typescript theme={null}
testdriver.disconnect(): Promise<void>
```

The Vitest hook calls this for you.

## auth()

Authenticates with the TestDriver API and resolves to a session token.

```typescript theme={null}
testdriver.auth(): Promise<string>
```

You rarely need it, because `connect()` calls it when needed.

## getInstance()

Returns the connected sandbox's details, or `null` if the client isn't connected.

```typescript theme={null}
testdriver.getInstance(): SandboxInstance | null
```

## getSessionId()

Returns the current session ID, or `null`. Include it when you report a problem.

```typescript theme={null}
testdriver.getSessionId(): string | null
```

## getLastSandboxId()

Returns the most recent sandbox, or `null` if there isn't one. It reads from the connected client, or from `.testdriver/last-sandbox`.

```typescript theme={null}
testdriver.getLastSandboxId(): { sandboxId: string; os?: 'windows' | 'linux'; createdAt?: number } | null
```

## setLogging(enabled)

Turns console logging on or off while the test runs.

```typescript theme={null}
testdriver.setLogging(enabled: boolean): void
```

## getEmitter()

Returns the client's event emitter, so you can react to what TestDriver does.

```typescript theme={null}
testdriver.getEmitter(): EventEmitter2
```

```javascript theme={null}
const emitter = testdriver.getEmitter();

emitter.on('log:warn', (message) => console.warn('TestDriver warning:', message));
emitter.on('error:sdk', (error) => console.error('TestDriver API error:', error.message));
```

See [Events](https://docs.testdriver.ai/events.md) for every event name.

## Related

* [Options](https://docs.testdriver.ai/options.md): every option you can pass to the client
* [Launch apps](https://docs.testdriver.ai/provision.md): start Chrome, extensions, and desktop apps once connected
* [Run tests](https://docs.testdriver.ai/copilot/running-tests.md#reuse-a-sandbox-while-you-iterate): reuse a sandbox between runs
* [Events](https://docs.testdriver.ai/events.md): listen for commands, logs, and errors


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