browsertest-sdk
v1.0.1
Published
JavaScript SDK for BrowserTest API - screenshots and agentic testing
Maintainers
Readme
BrowserTest SDK
A JavaScript/TypeScript SDK for the BrowserTest API - automated screenshots and agentic browser testing with natural language instructions.
Features
- 🚀 Fast Screenshots: Capture website screenshots with customizable options
- 🤖 Agentic Testing: Run browser tests using natural language instructions with AI agents
- 📝 Test Templates: Create reusable test templates with structured output schemas
- 📦 Batch Operations: Process multiple screenshots/tests efficiently
- 🔧 TypeScript Support: Full type definitions included
- 🛡️ Error Handling: Comprehensive error handling with retries
- 📊 Usage Tracking: Monitor API usage and quotas
- 🌐 ESM & CommonJS: Support for both module systems
- 📋 Async Job Management: Queue and monitor long-running test jobs
Installation
npm install browsertest-sdk
# or
yarn add browsertest-sdkQuick Start
import { BrowserTest } from 'browsertest-sdk';
// Initialize the SDK
const bt = new BrowserTest({
apiKey: 'your-api-key-here' // Get from https://browsertest.in
});
// Take a screenshot
const screenshot = await bt.screenshot.take({
url: 'https://example.com',
fullPage: true,
format: 'png'
});
console.log('Screenshot taken:', screenshot.data.screenshot.length, 'bytes');
// Run an agentic test with structured output
const testResult = await bt.testing.execute({
instructions: 'Test the login functionality with valid credentials',
url: 'https://example.com/login',
outputSchema: {
type: 'object',
properties: {
loginSuccessful: { type: 'boolean', description: 'Whether login succeeded' },
userName: { type: 'string', description: 'Logged in user name' },
errorMessage: { type: 'string', description: 'Any error message' }
}
}
});
console.log('Test completed:', testResult.results.structuredData);API Key
Get your API key from BrowserTest Dashboard. The SDK requires a valid API key for all operations.
Usage Examples
Screenshots
// Basic screenshot
const screenshot = await bt.screenshot.take({
url: 'https://example.com'
});
// Full page screenshot
const fullPage = await bt.screenshot.fullPage('https://example.com');
// Element screenshot
const element = await bt.screenshot.element(
'https://example.com',
'.hero-section'
);
// Batch screenshots
const batch = await bt.screenshot.takeBatch({
urls: [
'https://site1.com',
'https://site2.com',
'https://site3.com'
],
fullPage: true
});Agentic Testing
// Natural language test
const result = await bt.testing.test(
'Navigate to the products page and verify the search functionality works',
'https://example.com'
);
// Login test
const loginResult = await bt.testing.login(
'https://example.com/login',
{ email: '[email protected]', password: 'password123' }
);
// Form filling test
const formResult = await bt.testing.fillForm(
'https://example.com/contact',
{ name: 'John Doe', email: '[email protected]', message: 'Hello!' }
);Batch Operations
// Batch screenshots with concurrency control
const screenshotResults = await bt.batch.screenshots([
{ url: 'https://site1.com', fullPage: true },
{ url: 'https://site2.com', width: 1920, height: 1080 },
{ url: 'https://site3.com', format: 'jpeg', quality: 90 }
], { concurrency: 2 });
// Batch tests
const testResults = await bt.batch.tests([
{
instructions: 'Check if the homepage loads correctly',
url: 'https://example.com'
},
{
instructions: 'Verify the contact form validation',
url: 'https://example.com/contact'
}
]);Async Test Jobs
Async jobs are created by invoking templates. Use the template system for complex, long-running tests.
// First create a template (see Templates section above)
const template = await bt.template.create({
name: 'Complex Checkout Flow',
instructions: 'Perform a complete e-commerce checkout flow test',
// ... template configuration
});
// Invoke template to create async job
const job = await bt.template.invoke(template.template.id, {
url: 'https://example-shop.com/checkout'
});
console.log('Job created:', job.jobId, 'Status:', job.status);
// Check job status
const status = await bt.testing.getStatus(job.jobId);
console.log('Job status:', status.job.status);
// List all jobs
const jobs = await bt.testing.list({
limit: 10,
status: 'completed',
templateId: template.template.id // Filter by template
});Test Templates
Templates allow you to create reusable test configurations with structured output schemas.
// Create a test template
const template = await bt.template.create({
name: 'E-commerce Checkout Test',
description: 'Test the complete checkout flow',
instructions: `
Navigate to the product page.
Add item to cart.
Proceed to checkout.
Fill in shipping and payment details.
Complete the purchase.
`,
outputSchema: {
type: 'object',
properties: {
checkoutSuccessful: {
type: 'boolean',
description: 'Whether checkout completed successfully'
},
orderNumber: {
type: 'string',
description: 'Order confirmation number if available'
},
totalAmount: {
type: 'string',
description: 'Total order amount'
},
errors: {
type: 'array',
items: { type: 'string' },
description: 'Any errors encountered during checkout'
}
}
},
tags: ['checkout', 'e-commerce', 'purchase']
});
// List templates
const templates = await bt.template.list({
search: 'checkout',
tags: ['e-commerce'],
limit: 20
});
// Invoke a template (creates async job)
const job = await bt.template.invoke(template.template.id, {
url: 'https://example-shop.com/product/123',
config: {
viewport: { width: 1920, height: 1080 },
waitFor: 3000
}
});
// Create and invoke in one step
const result = await bt.template.createAndInvoke({
name: 'Quick Page Check',
instructions: 'Check if the page loads without errors',
url: 'https://example.com'
});Configuration
const bt = new BrowserTest({
apiKey: 'your-api-key',
baseUrl: 'https://api.browsertest.in', // Optional
timeout: 30000, // Request timeout in ms
retries: 3 // Number of retries for failed requests
});Error Handling
The SDK provides specific error types for different scenarios:
try {
const result = await bt.screenshot.take({ url: 'https://example.com' });
} catch (error) {
if (error.name === 'BrowserTestAuthError') {
console.log('Invalid API key');
} else if (error.name === 'BrowserTestQuotaError') {
console.log('Quota exceeded:', error.quotaInfo);
} else if (error.name === 'BrowserTestAPIError') {
console.log('API error:', error.status);
}
}Usage Tracking
// Check current usage
const usage = await bt.getUsage();
console.log('Screenshots used:', usage.usage.screenshot.used);
console.log('Agentic tests used:', usage.usage.agentic.used);
// Check if connection is working
const isConnected = await bt.testConnection();
console.log('API connection:', isConnected ? 'OK' : 'Failed');TypeScript Support
import { BrowserTest, ScreenshotOptions, TestResult } from 'browsertest-sdk';
const bt = new BrowserTest({
apiKey: process.env.BROWSERTEST_API_KEY!
});
// Fully typed
const options: ScreenshotOptions = {
url: 'https://example.com',
fullPage: true,
format: 'png'
};
const result: TestResult = await bt.testing.execute({
instructions: 'Test the homepage',
url: 'https://example.com'
});API Reference
BrowserTest Class
constructor(config: BrowserTestConfig)testConnection(): Promise<boolean>getUsage(): Promise<QuotaInfo>
ScreenshotAPI Class
take(options: ScreenshotOptions): Promise<ScreenshotResult>takeBatch(options: BatchScreenshotOptions): Promise<BatchScreenshotResult>screenshot(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>fullPage(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>element(url: string, selector: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>
TestingAPI Class
execute(options: TestOptions): Promise<TestResult>create(options: TestOptions): Promise<TestJob>getStatus(jobId: string): Promise<TestJobStatus>list(options?: ListTestsOptions): Promise<TestJobsList>test(instructions: string, url: string, options?: TestExecutionOptions): Promise<TestResult>login(url: string, credentials: LoginCredentials, options?: Partial<TestOptions>): Promise<TestResult>fillForm(url: string, formData: object, options?: Partial<TestOptions>): Promise<TestResult>
BatchAPI Class
screenshots(requests: ScreenshotRequest[], options?: BatchOptions): Promise<BatchScreenshotResults>tests(requests: TestRequest[], options?: BatchOptions): Promise<BatchTestResults>createTests(requests: TestRequest[]): Promise<BatchJobResults>
Rate Limits & Quotas
- Free plan: 100 screenshots/month, 50 agentic tests/month
- Starter plan: 1,000 screenshots/month, 100 agentic tests/month
- Pro plan: 10,000 screenshots/month, 500 agentic tests/month
- Enterprise: Custom limits
Check your usage with getUsage() to avoid hitting limits.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see the LICENSE file for details.
