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

# BrowserTest Class

> Main SDK class for BrowserTest API integration

## Constructor

```typescript theme={null}
new BrowserTest(config: BrowserTestConfig)
```

### Parameters

| Parameter | Type                | Required | Description                      |
| --------- | ------------------- | -------- | -------------------------------- |
| `config`  | `BrowserTestConfig` | Yes      | Configuration object for the SDK |

### BrowserTestConfig

```typescript theme={null}
interface BrowserTestConfig {
  /** API key for authentication */
  apiKey: string;
  /** Base URL for API calls (default: https://api.browsertest.in) */
  baseUrl?: string;
  /** Request timeout in milliseconds (default: 30000) */
  timeout?: number;
  /** Number of retries for failed requests (default: 3) */
  retries?: number;
}
```

### Example

```javascript theme={null}
import { BrowserTest } from 'browsertest-sdk';

const bt = new BrowserTest({
  apiKey: process.env.BROWSERTEST_API_KEY,
  baseUrl: 'https://api.browsertest.in', // Optional
  timeout: 30000, // Optional
  retries: 3 // Optional
});
```

## Instance Properties

### screenshot

`ScreenshotAPI` - Methods for capturing website screenshots

**Type:** `ScreenshotAPI`

### testing

`TestingAPI` - Methods for agentic testing and job management

**Type:** `TestingAPI`

### template

`TemplateAPI` - Methods for managing test templates

**Type:** `TemplateAPI`

### batch

`BatchAPI` - Methods for batch operations

**Type:** `BatchAPI`

## Instance Methods

### testConnection()

Tests if the API connection is working and the API key is valid.

```typescript theme={null}
testConnection(): Promise<boolean>
```

#### Returns

`Promise<boolean>` - `true` if connection is successful, `false` otherwise

#### Example

```javascript theme={null}
const isConnected = await bt.testConnection();
console.log('API Connection:', isConnected ? 'OK' : 'Failed');
```

### getUsage()

Retrieves current API usage and quota information.

```typescript theme={null}
getUsage(): Promise<QuotaInfo>
```

#### Returns

`Promise<QuotaInfo>` - Usage statistics and quota limits

#### QuotaInfo

```typescript theme={null}
interface QuotaInfo {
  plan: string;
  usage: {
    screenshot: {
      used: number;
      limit: number;
      remaining: number;
    };
    agentic: {
      used: number;
      limit: number;
      remaining: number;
    };
    total: {
      screenshot: number;
      agentic: number;
    };
  };
}
```

#### Example

```javascript theme={null}
const usage = await bt.getUsage();
console.log('Current plan:', usage.plan);
console.log('Screenshots remaining:', usage.usage.screenshot.remaining);
console.log('Agentic tests remaining:', usage.usage.agentic.remaining);
```

## Error Types

The SDK throws specific error types for different scenarios:

### BrowserTestAuthError

Thrown when API key is invalid or authentication fails.

```javascript theme={null}
try {
  await bt.screenshot.take({ url: 'https://example.com' });
} catch (error) {
  if (error.name === 'BrowserTestAuthError') {
    console.log('Authentication failed - check your API key');
  }
}
```

### BrowserTestQuotaError

Thrown when API quota is exceeded.

```javascript theme={null}
try {
  await bt.testing.execute({ instructions: 'test', url: 'https://example.com' });
} catch (error) {
  if (error.name === 'BrowserTestQuotaError') {
    console.log('Quota exceeded:', error.quotaInfo);
  }
}
```

### BrowserTestAPIError

Thrown for general API errors.

```javascript theme={null}
try {
  await bt.screenshot.take({ url: 'https://example.com' });
} catch (error) {
  if (error.name === 'BrowserTestAPIError') {
    console.log('API error:', error.status, error.message);
  }
}
```

### BrowserTestTimeoutError

Thrown when requests timeout.

```javascript theme={null}
try {
  await bt.testing.execute({
    instructions: 'complex test',
    url: 'https://example.com'
  });
} catch (error) {
  if (error.name === 'BrowserTestTimeoutError') {
    console.log('Request timed out - try simplifying your test');
  }
}
```

## Configuration Examples

### Basic Configuration

```javascript theme={null}
const bt = new BrowserTest({
  apiKey: 'your-api-key-here'
});
```

### Advanced Configuration

```javascript theme={null}
const bt = new BrowserTest({
  apiKey: process.env.BROWSERTEST_API_KEY,
  baseUrl: 'https://api.browsertest.in',
  timeout: 60000, // 1 minute for complex operations
  retries: 5 // More retries for unreliable networks
});
```

### Environment-Based Configuration

```javascript theme={null}
const config = {
  development: {
    apiKey: process.env.BROWSERTEST_DEV_KEY,
    timeout: 30000,
    retries: 1
  },
  staging: {
    apiKey: process.env.BROWSERTEST_STAGING_KEY,
    timeout: 45000,
    retries: 3
  },
  production: {
    apiKey: process.env.BROWSERTEST_PROD_KEY,
    timeout: 60000,
    retries: 5
  }
};

const environment = process.env.NODE_ENV || 'development';
const bt = new BrowserTest(config[environment]);
```

## Best Practices

### API Key Security

```javascript theme={null}
// ❌ Bad - hardcoded API key
const bt = new BrowserTest({
  apiKey: 'sk-1234567890abcdef'
});

// ✅ Good - environment variable
const bt = new BrowserTest({
  apiKey: process.env.BROWSERTEST_API_KEY
});

// ✅ Better - validation
if (!process.env.BROWSERTEST_API_KEY) {
  throw new Error('BROWSERTEST_API_KEY environment variable is required');
}

const bt = new BrowserTest({
  apiKey: process.env.BROWSERTEST_API_KEY
});
```

### Error Handling

```javascript theme={null}
class BrowserTestWrapper {
  constructor(config) {
    this.bt = new BrowserTest(config);
  }

  async safeOperation(operation, ...args) {
    try {
      return await operation.apply(this.bt, args);
    } catch (error) {
      console.error('BrowserTest operation failed:', error.message);

      // Handle specific error types
      switch (error.name) {
        case 'BrowserTestAuthError':
          throw new Error('Invalid API key - please check your configuration');
        case 'BrowserTestQuotaError':
          throw new Error(`API quota exceeded. Used: ${error.quotaInfo?.usage?.total || 'unknown'}`);
        case 'BrowserTestTimeoutError':
          throw new Error('Operation timed out - try again or simplify your request');
        default:
          throw error;
      }
    }
  }
}
```

### Connection Testing

```javascript theme={null}
async function initializeBrowserTest() {
  const bt = new BrowserTest({
    apiKey: process.env.BROWSERTEST_API_KEY
  });

  // Test connection before proceeding
  const isConnected = await bt.testConnection();
  if (!isConnected) {
    throw new Error('Failed to connect to BrowserTest API');
  }

  // Check usage
  const usage = await bt.getUsage();
  console.log(`Connected to BrowserTest (${usage.plan} plan)`);
  console.log(`Usage: ${usage.usage.screenshot.used}/${usage.usage.screenshot.limit} screenshots`);

  return bt;
}
```

### Resource Cleanup

```javascript theme={null}
class BrowserTestManager {
  constructor() {
    this.instances = new Map();
  }

  getInstance(configKey) {
    if (!this.instances.has(configKey)) {
      const config = this.getConfig(configKey);
      this.instances.set(configKey, new BrowserTest(config));
    }
    return this.instances.get(configKey);
  }

  getConfig(configKey) {
    // Load configuration based on key
    const configs = {
      default: {
        apiKey: process.env.BROWSERTEST_API_KEY,
        timeout: 30000
      },
      extended: {
        apiKey: process.env.BROWSERTEST_API_KEY,
        timeout: 60000,
        retries: 5
      }
    };
    return configs[configKey] || configs.default;
  }

  async cleanup() {
    // Close any persistent connections if needed
    this.instances.clear();
  }
}

// Usage
const manager = new BrowserTestManager();
const bt = manager.getInstance('extended');

// Use bt...

// Cleanup when done
process.on('SIGINT', async () => {
  await manager.cleanup();
  process.exit(0);
});
```
