@carthooks/test-context
Version:
A test context manager for sharing data across test files in E2E testing
281 lines (203 loc) • 6.55 kB
Markdown
# @carthooks/test-context
A powerful test context manager for sharing data across test files in E2E testing. Built with TypeScript and designed to work seamlessly with Playwright, Jest, Vitest, and other testing frameworks.
## Features
- 🔄 **Cross-test data sharing** - Share authentication tokens, entity IDs, and other test data between test files
- 🎯 **Type-safe** - Full TypeScript support with generics
- 🔌 **Framework agnostic** - Works with Playwright, Jest, Vitest, and more
- 🧩 **Plugin system** - Extend functionality with custom plugins
- 💾 **Persistent storage** - Data persists between test runs
- 🔍 **Dependency checking** - Ensure required data is available before running tests
- 📊 **Metrics & logging** - Built-in logging and usage metrics
## Installation
```bash
npm install @carthooks/testContext
# or
yarn add @carthooks/testContext
# or
pnpm add @carthooks/testContext
```
## Quick Start
### Playwright
```typescript
import { createPlaywrightTest, expect } from '@carthooks/testContext';
const test = createPlaywrightTest({
contextPath: './test-data/context.json',
autoSave: true
});
test('Login and store token', async ({ testContext }) => {
const token = 'your-auth-token';
testContext.set('auth.token', token);
testContext.set('user.id', '12345');
});
test('Use stored token', async ({ testContext }) => {
const token = testContext.require<string>('auth.token');
const userId = testContext.require<string>('user.id');
// Use the token for API calls
expect(token).toBeDefined();
});
```
### Jest
```typescript
import { setupJestTestContext, withTestContext } from '@carthooks/testContext';
// Setup in your test file
const { beforeAll, afterAll } = withTestContext({
contextPath: './test-data/context.json'
});
beforeAll(() => {
setupJestTestContext();
});
test('Store and retrieve data', () => {
global.testContext.set('api.url', 'https://api.example.com');
const url = global.testContext.require<string>('api.url');
expect(url).toBe('https://api.example.com');
});
```
### Vitest
```typescript
import { setupVitestTestContext, withVitestTestContext } from '@carthooks/testContext';
const { beforeAll, afterAll } = withVitestTestContext();
beforeAll(() => {
setupVitestTestContext();
});
test('Store and retrieve data', () => {
global.testContext.set('api.url', 'https://api.example.com');
const url = global.testContext.require<string>('api.url');
expect(url).toBe('https://api.example.com');
});
```
## API Reference
### TestContext
#### Configuration
```typescript
interface TestContextConfig {
contextPath?: string; // Default: '.test-context/context.json'
autoSave?: boolean; // Default: true
logger?: Logger; // Custom logger instance
contextDir?: string; // Default: '.test-context'
}
```
#### Core Methods
```typescript
// Set a value
testContext.set(key: string, value: any): void
// Get a value (returns undefined if not found)
testContext.get<T>(key: string): T | undefined
// Get a value (throws error if not found)
testContext.require<T>(key: string): T
// Check if key exists
testContext.has(key: string): boolean
// Delete a key
testContext.delete(key: string): void
// Clear all data
testContext.clear(): void
// Get all keys
testContext.keys(): string[]
// Get data size
testContext.size(): number
// Check dependencies
testContext.checkDependencies(required: string[]): DependencyCheck
```
#### Utility Methods
```typescript
// Export context to file
testContext.export(filePath?: string): void
// Import context from file
testContext.import(filePath: string): void
// Get JSON representation
testContext.toJSON(): Record<string, any>
// Load from JSON
testContext.fromJSON(data: Record<string, any>): void
```
## Plugins
### Validation Plugin
```typescript
import { TestContext, ValidationPlugin } from '@carthooks/testContext';
const testContext = TestContext.create();
testContext.use(new ValidationPlugin());
// Mark keys as required
(testContext as any).addRequiredKey('auth.token');
(testContext as any).addRequiredKey('user.id');
// Validate all required keys are present
(testContext as any).validateRequired();
```
### Persistence Plugin
```typescript
import { TestContext, PersistencePlugin } from '@carthooks/testContext';
const testContext = TestContext.create();
testContext.use(new PersistencePlugin());
// Auto-saves every 30 seconds
```
### Metrics Plugin
```typescript
import { TestContext, MetricsPlugin } from '@carthooks/testContext';
const testContext = TestContext.create();
testContext.use(new MetricsPlugin());
// Get usage metrics
const metrics = (testContext as any).getMetrics();
console.log(metrics); // { set: 5, get: 10, delete: 1 }
```
## Advanced Usage
### Custom Logger
```typescript
import { TestContext, type Logger } from '@carthooks/testContext';
class CustomLogger implements Logger {
info(message: string, ...args: any[]): void {
console.log(`[CUSTOM] ${message}`, ...args);
}
// ... implement other methods
}
const testContext = TestContext.create({
logger: new CustomLogger()
});
```
### Multiple Context Instances
```typescript
import { TestContext } from '@carthooks/testContext';
// Create separate instances for different test suites
const authContext = TestContext.create({
contextPath: './test-data/auth-context.json'
});
const dataContext = TestContext.create({
contextPath: './test-data/data-context.json'
});
```
### Dependency Management
```typescript
// Check if all required data is available
const deps = testContext.checkDependencies([
'auth.token',
'user.id',
'api.baseUrl'
]);
if (!deps.satisfied) {
throw new Error(`Missing dependencies: ${deps.missing.join(', ')}`);
}
```
## Migration from Existing TestContext
If you're migrating from an existing TestContext implementation:
1. Install the package: `npm install @carthooks/testContext`
2. Update your imports:
```typescript
// Before
import { testContext } from './context/TestContext';
// After
import { createPlaywrightTest } from '@carthooks/testContext';
const test = createPlaywrightTest();
```
3. Update your test files to use the new API
4. Remove the old TestContext files
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
## License
MIT
## Changelog
### 1.0.0
- Initial release
- Core TestContext functionality
- Playwright, Jest, and Vitest adapters
- Plugin system
- TypeScript support