@carthooks/test-context
v1.0.1
Published
A test context manager for sharing data across test files in E2E testing
Maintainers
Readme
@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
npm install @carthooks/testContext
# or
yarn add @carthooks/testContext
# or
pnpm add @carthooks/testContextQuick Start
Playwright
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
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
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
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
// 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[]): DependencyCheckUtility Methods
// 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>): voidPlugins
Validation Plugin
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
import { TestContext, PersistencePlugin } from '@carthooks/testContext';
const testContext = TestContext.create();
testContext.use(new PersistencePlugin());
// Auto-saves every 30 secondsMetrics Plugin
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
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
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
// 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:
- Install the package:
npm install @carthooks/testContext - Update your imports:
// Before import { testContext } from './context/TestContext'; // After import { createPlaywrightTest } from '@carthooks/testContext'; const test = createPlaywrightTest(); - Update your test files to use the new API
- Remove the old TestContext files
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
MIT
Changelog
1.0.0
- Initial release
- Core TestContext functionality
- Playwright, Jest, and Vitest adapters
- Plugin system
- TypeScript support
