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

@blaizejs/testing-utils

v0.6.0

Published

Comprehensive testing utilities for BlaizeJS applications including middleware testing, plugin lifecycle simulation, context mocking, and integration test helpers with full TypeScript support.

Readme

@blaizejs/testing-utils

Comprehensive testing utilities for BlaizeJS applications with full TypeScript support.

Installation

npm install --save-dev @blaizejs/testing-utils
# or
pnpm add -D @blaizejs/testing-utils
# or
yarn add -D @blaizejs/testing-utils

Features

  • Route Testing Helpers - Simplified setup for route handler tests
  • Mock Logger - With assertion helpers for cleaner tests
  • Mock EventBus - With assertion helpers for event validation
  • Context Mocking - Full request/response context creation
  • SSE Testing - Server-Sent Events stream mocking
  • Middleware Testing - Test middleware in isolation
  • Plugin Testing - Test plugin lifecycle and behavior
  • Server Mocking - Full server instance mocking
  • TypeScript Support - Full type safety and inference

Quick Start

Testing Routes (Recommended Pattern)

The easiest way to test route handlers is with createRouteTestContext():

import { createRouteTestContext } from '@blaizejs/testing-utils';
import { describe, it, expect } from 'vitest';
import { getUserById } from '../routes/users/[userId]';

describe('GET /users/:userId', () => {
  it('should fetch user and publish event', async () => {
    const { logger, eventBus, cleanup } = createRouteTestContext();

    const result = await getUserById.handler({
      params: { userId: 'test-123' },
      logger,
      eventBus,
    });

    expect(result.id).toBe('test-123');
    
    // Assert logging
    logger.assertInfoCalled('Fetching user', { userId: 'test-123' });
    
    // Assert events
    eventBus.assertPublished('user:viewed', { userId: 'test-123' });

    cleanup();
  });
});

Benefits:

  • 1 line of setup instead of 15+
  • Automatic cleanup with cleanup()
  • Assertion helpers built-in
  • Type-safe by default

Route Testing Helpers

createRouteTestContext()

Creates a complete test context with logger, eventBus, and cleanup function.

Returns:

  • logger - MockLogger with assertion helpers
  • eventBus - MockEventBus with assertion helpers
  • cleanup() - Resets all mocks and state

Example:

import { createRouteTestContext } from '@blaizejs/testing-utils';

describe('User Routes', () => {
  it('should create user', async () => {
    const { logger, eventBus, cleanup } = createRouteTestContext();

    await createUser.handler({
      body: { name: 'John Doe', email: '[email protected]' },
      logger,
      eventBus,
    });

    logger.assertInfoCalled('User created');
    eventBus.assertPublished('user:created', {
      email: '[email protected]',
    });

    cleanup();
  });
});

With beforeEach/afterEach:

describe('User Routes', () => {
  const { logger, eventBus, cleanup } = createRouteTestContext();

  afterEach(() => {
    cleanup(); // Reset state between tests
  });

  it('test 1', async () => {
    // Use logger and eventBus
  });

  it('test 2', async () => {
    // Fresh state from cleanup
  });
});

Mock Logger

createMockLogger()

Creates a mock logger with tracking and assertion helpers.

Assertion Methods:

  • assertInfoCalled(message, meta?) - Assert info log was called
  • assertDebugCalled(message, meta?) - Assert debug log was called
  • assertWarnCalled(message, meta?) - Assert warn log was called
  • assertErrorCalled(message, meta?) - Assert error log was called

Helper Methods:

  • getLogsByLevel(level) - Get all logs for a specific level
  • clear() - Reset all tracked logs

Example:

import { createMockLogger } from '@blaizejs/testing-utils';

const logger = createMockLogger();

// Log something
logger.info('User created', { userId: '123', email: '[email protected]' });

// Assert it was called
logger.assertInfoCalled('User created', { userId: '123' });

// Get all info logs
const infoLogs = logger.getLogsByLevel('info');
console.log(infoLogs); // [{ message: 'User created', meta: {...} }]

// Clear for next test
logger.clear();

Partial Meta Matching:

logger.info('Request processed', {
  userId: '123',
  timestamp: 1234567890,
  ip: '192.168.1.1',
  extra: 'data',
});

// Only check userId - other fields ignored
logger.assertInfoCalled('Request processed', { userId: '123' });

Mock EventBus

createMockEventBus()

Creates a mock EventBus with tracking and assertion helpers.

Assertion Methods:

  • assertPublished(eventType, data?) - Assert event was published
  • assertNotPublished(eventType) - Assert event was NOT published

Helper Methods:

  • getPublishedEvents(eventType?) - Get published events (optionally filtered)
  • clear() - Reset all tracked events

Example:

import { createMockEventBus } from '@blaizejs/testing-utils';

const eventBus = createMockEventBus();

// Publish events
await eventBus.publish('user:created', { userId: '123' });
await eventBus.publish('email:sent', { to: '[email protected]' });

// Assert they were published
eventBus.assertPublished('user:created', { userId: '123' });
eventBus.assertPublished('email:sent');

// Assert event was NOT published
eventBus.assertNotPublished('user:deleted');

// Get all published events
const events = eventBus.getPublishedEvents();
console.log(events.length); // 2

// Get events by type
const userEvents = eventBus.getPublishedEvents('user:created');
console.log(userEvents.length); // 1

// Clear for next test
eventBus.clear();

Partial Data Matching:

await eventBus.publish('order:placed', {
  orderId: '456',
  total: 99.99,
  items: [...],
  timestamp: 1234567890,
});

// Only check orderId - other fields ignored
eventBus.assertPublished('order:placed', { orderId: '456' });

Context Mocking

createMockContext()

Creates a mock context object for testing handlers.

Example:

import { createMockContext } from '@blaizejs/testing-utils';

const ctx = createMockContext({
  method: 'GET',
  path: '/api/users',
  query: { page: '1' },
  params: { userId: '123' },
});

// Use in handler
const result = await handler({ ctx, logger, eventBus });

With Request Body:

const ctx = createMockContext({
  method: 'POST',
  path: '/api/users',
  body: {
    name: 'John Doe',
    email: '[email protected]',
  },
});

SSE Testing

createSSEMockContext()

Creates a mock context with SSE stream support.

Example:

import { createSSEMockContext } from '@blaizejs/testing-utils';

const { ctx, stream } = createSSEMockContext();

// Test SSE handler
await sseHandler({ ctx, logger, eventBus });

// Verify stream was set up
expect(stream.send).toHaveBeenCalled();
expect(stream.onClose).toHaveBeenCalled();

Middleware Testing

createMockMiddleware()

Creates a mock middleware for testing.

Example:

import { createMockMiddleware } from '@blaizejs/testing-utils';

const middleware = createMockMiddleware({
  name: 'test-middleware',
  execute: async ({ ctx, next }) => {
    ctx.state.testValue = 'test';
    await next();
  },
});

// Test middleware
await middleware.execute({
  ctx,
  next: async () => {},
  logger,
  eventBus,
});

expect(ctx.state.testValue).toBe('test');

Server Mocking

createMockServer()

Creates a mock server instance for testing plugins and lifecycle.

Example:

import { createMockServer } from '@blaizejs/testing-utils';

const server = createMockServer();

// Test plugin
await plugin.register(server);
await plugin.initialize(server);

expect(server.plugins).toContainEqual(plugin);

Migration from 0.5.x to 0.6.0

New: createRouteTestContext

Before:

const logger = createMockLogger();
const eventBus = createMockEventBus();

// ... test code ...

logger.clear();
eventBus.clear();
vi.clearAllMocks();

After:

const { logger, eventBus, cleanup } = createRouteTestContext();

// ... test code ...

cleanup();

New: Logger Assertion Helpers

Before:

expect(logger.info).toHaveBeenCalledWith('User created', { userId: '123' });

After:

logger.assertInfoCalled('User created', { userId: '123' });

New: EventBus Assertion Helpers

Before:

expect(eventBus.publish).toHaveBeenCalledWith('user:created', { userId: '123' });

After:

eventBus.assertPublished('user:created', { userId: '123' });

TypeScript Support

All utilities have full TypeScript support with type inference:

import type { RouteTestContext } from '@blaizejs/testing-utils';

// Type-safe context
const context: RouteTestContext = createRouteTestContext();

// Inferred types
const logger = createMockLogger(); // MockLogger
const eventBus = createMockEventBus(); // TypedEventBus & MockEventBusHelpers

API Reference

Route Testing

  • createRouteTestContext<TSchemas>() - Create complete test context

Logger

  • createMockLogger() - Create mock logger
  • MockLogger - TypeScript type for mock logger

EventBus

  • createMockEventBus<TSchemas>() - Create mock event bus
  • createWorkingMockEventBus(serverId?) - Create working mock with pub/sub
  • MockEventBusHelpers - TypeScript type for assertion helpers

Context

  • createMockContext(options) - Create mock context
  • createSSEMockContext() - Create mock context with SSE

Middleware

  • createMockMiddleware(options) - Create mock middleware

Server

  • createMockServer(overrides?) - Create mock server
  • createMockServerWithPlugins(plugins) - Create mock server with plugins

Routes

  • mockGetRoute() - Create mock GET route
  • mockPostRoute() - Create mock POST route
  • mockPutRoute() - Create mock PUT route
  • mockPatchRoute() - Create mock PATCH route
  • mockDeleteRoute() - Create mock DELETE route

Contributing

See CONTRIBUTING.md for details on contributing to BlaizeJS.


License

MIT © J.Lea-Jones


Built with ❤️ by the BlaizeJS team