npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@carthooks/test-context

v1.0.1

Published

A test context manager for sharing data across test files in E2E testing

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/testContext

Quick 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[]): DependencyCheck

Utility 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>): void

Plugins

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 seconds

Metrics 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:

  1. Install the package: npm install @carthooks/testContext
  2. Update your imports:
    // 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