@sadikkhan02/test-utils

中文文档
1.0.0发布于 2026/11/02MITTypeScriptES Module零依赖

Deterministic testing utilities and adapter contract compliance suite for NotifyKit

原始使用文档
文档目录8 节
  1. Installation
  2. 1. Adapter Contract Test Suite
  3. Example: Running the Contract Suite
  4. What runAdapterContractTests Asserts
  5. 2. In-Memory Mock Providers
  6. 3. Deterministic Test Fixtures
  7. 4. Safe Local Redis Helpers
  8. License

@sadikkhan02/test-utils

The official test utilities and adapter contract testing framework for NotifyKit.

Provides shared fixtures, in-memory mock providers, safe local Redis helpers, and the standardized Adapter Contract Suite (runAdapterContractTests) required for all official and community provider adapters.


Installation

npm install --save-dev @sadikkhan02/test-utils vitest

1. Adapter Contract Test Suite

Every NotifyKit adapter (email, SMS, push) must conform to the standard provider interface and error classification contract. Using runAdapterContractTests, you can validate your custom adapter in minutes.

Example: Running the Contract Suite

import { describe, it, expect, vi } from 'vitest';
import { runAdapterContractTests } from '@sadikkhan02/test-utils';
import { MyEmailProvider, metadata } from '../src/index.js';

runAdapterContractTests({
  providerName: 'my-email',
  channel: 'email',
  metadata,
  createSuccessProvider: () => new MyEmailProvider({ mockTransport: true }),
  createAuthFailingProvider: () => new MyEmailProvider({ authError: true }),
  createNetworkFailingProvider: () => new MyEmailProvider({ networkError: true }),
  validOptions: {
    to: '[email protected]',
    from: '[email protected]',
    subject: 'Welcome',
    html: '<h1>Welcome!</h1>',
  },
  invalidOptions: {
    to: '',
    from: '',
    subject: '',
    html: '',
  },
  sampleSecret: 'my-secret-key-12345',
});

What runAdapterContractTests Asserts

  1. Metadata Conformance: Validates metadata.name, metadata.channel, and non-empty requiredEnv.
  2. Provider Identity: Checks provider.name === metadata.name and ensures the canonical delivery method (sendEmail, sendSms, or sendPush) is implemented.
  3. Delivery Success: Asserts { success: true, messageId: string } on successful delivery.
  4. Permanent Failure Classification: Asserts { success: false, retryable: false } with actionable error on auth/credential failures.
  5. Transient Failure Classification: Asserts { success: false, retryable: true } with actionable error on network/timeout failures.
  6. Malformed Input Safety: Asserts provider returns { success: false, retryable: false } gracefully on malformed inputs without throwing unhandled exceptions.
  7. Zero Credential Exposure: Verifies raw secrets, bearer tokens, and private key headers are never leaked in returned error messages.

2. In-Memory Mock Providers

Easily simulate notification delivery in application unit and integration tests without network I/O or credentials:

import {
  createMockEmailProvider,
  createMockSmsProvider,
  createMockPushProvider,
} from '@sadikkhan02/test-utils';

const mockEmail = createMockEmailProvider({ name: 'test-smtp' });
const mockSms = createMockSmsProvider({ name: 'test-sms' });

// Send a test email
await mockEmail.sendEmail({
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Test',
  html: '<p>Test</p>',
});

// Inspect recorded calls
console.log(mockEmail.calls.length); // 1
console.log(mockEmail.calls[0].to); // '[email protected]'

// Simulate failure
mockEmail.setResult({ success: false, error: 'Rate limit exceeded', retryable: true });

3. Deterministic Test Fixtures

Generate consistent, schema-valid recipients, jobs, and results:

import {
  createTestRecipient,
  createTestNotificationJob,
  createMockProviderResult,
} from '@sadikkhan02/test-utils';

const emailRecipient = createTestRecipient('email', { email: '[email protected]' });
const smsRecipient = createTestRecipient('sms');
const pushRecipient = createTestRecipient('push');

const job = createTestNotificationJob('email', {
  templateId: 'order-confirmed',
  variables: { orderId: '123' },
});

4. Safe Local Redis Helpers

When running integration tests with real Redis, prevent accidental execution against remote or production instances:

import { isSafeLocalRedisUrl, cleanupTestRedis } from '@sadikkhan02/test-utils';

// Fails closed if REDIS_URL is not 127.0.0.1 or localhost
await cleanupTestRedis();

License

MIT

版本与发布记录

@sadikkhan02/test-utils 共发布 2 个版本,首次发布于 2026/11/02;过去 12 个月发布了 2 个版本。

版本发布日期距今
1.0.0latest2026/11/021 天前
0.0.0-stage2026/11/021 天前

关于 @sadikkhan02/test-utils 的常见问题

@sadikkhan02/test-utils 是什么?

用于NotifyKit的确定性测试实用程序和适配器契约遵从套件

如何安装 @sadikkhan02/test-utils?

在项目目录运行 npm install @sadikkhan02/test-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:vitest(>=1.0.0 || >=2.0.0 || >=3.0.0 || >=4.0.0 || >=5.0.0)、@sadikkhan02/notifykit(^1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@sadikkhan02/test-utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@sadikkhan02/test-utils 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@sadikkhan02/test-utils 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@sadikkhan02/test-utils 可以商用吗?

@sadikkhan02/test-utils 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@sadikkhan02/test-utils 还在维护吗?

最新版本 1.0.0 发布于 2026/11/02(1 天前);至今共发布 2 个版本,其中过去 12 个月发布了 2 个;首次发布于 2026/11/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。