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

@itd-api/testing

v0.1.0

Published

Средства тестирования клиентов и плагинов itd-api без сетевых запросов

Readme

@itd-api/testing

Сценарные ответы, сервер API в памяти, заготовки данных и управляемый realtime для тестирования itd-api без сетевых запросов.

Руководство · API из TSDoc

Установка

npm install itd-api
npm install --save-dev @itd-api/testing

Поддерживается itd-api >=0.5.0 <1.0.0.

Сервер с состоянием

import { ItdClient } from 'itd-api';
import { createMockServer } from '@itd-api/testing';

const server = createMockServer({
  seed: {
    users: [
      { id: 'user-alice', username: 'alice' },
      { id: 'user-bob', username: 'bob' },
    ],
  },
});

const alice = new ItdClient(server.clientOptions({ as: 'alice' }));
const bob = new ItdClient(server.clientOptions({ as: 'bob' }));

const post = await alice.posts.create({ content: 'Проверяем сценарий' });
await bob.posts.like(post.id);

expect((await alice.posts.get(post.id)).likesCount).toBe(1);

Оба клиента работают с одним состоянием. Сервер поддерживает профили, записи, комментарии и ответы, реакции, подписки, уведомления, удаление и восстановление. Неизвестный маршрут возвращает статус 501 с кодом MOCK_ROUTE_NOT_IMPLEMENTED. Некорректные связи и повторяющиеся идентификаторы в seed отклоняются до изменения состояния.

Сценарный fetch

import { ItdClient } from 'itd-api';
import { apiErrorResponse, apiResponse, createMockFetch, userFixture } from '@itd-api/testing';

const mock = createMockFetch();
mock.get('/api/users/me', [
  apiErrorResponse(503, 'TEMPORARY', 'Повторите запрос'),
  apiResponse(userFixture()),
]);

const itd = new ItdClient({ fetch: mock.fetch, auth: 'test-token' });
await itd.users.me();
mock.assertDone();

Маршруты принимают параметры вида /api/posts/:postId. Обработчик получает разобранные query-параметры, заголовки, JSON, FormData, текст и двоичное тело. История в mock.requests скрывает токены, cookie, пароли, OTP и Turnstile-токены. sseResponse() создаёт настоящий поток Server-Sent Events для проверки SSE-разбора.

Моки логических операций

Когда HTTP-детали не являются предметом теста, подменяйте стабильный operationId:

import { ItdClient } from 'itd-api';
import { createMockOperations, userFixture } from '@itd-api/testing';

const mock = createMockOperations().operation('users.me', userFixture({ username: 'alice' }));
const itd = new ItdClient({ auth: 'test-token' }).use(mock);

await itd.users.me();
mock.assertDone();

Такой mock завершает логическую операцию до retry, auth и transport. Для проверки 401, повторов, заголовков и сериализации по-прежнему используйте createMockFetch().

Управляемое время и realtime

import { createTestClock, MockRealtimeTransport } from '@itd-api/testing';

const clock = createTestClock('2026-08-01T10:00:00Z');
const transport = new MockRealtimeTransport();

const itd = new ItdClient({ auth: 'test-token', clock });
const stream = itd.realtime({ transport, syncCount: false, jitter: 0 });
await stream.connect();
await transport.waitForConnection(0);

transport.unreadCount(3);
await stream.drain();

await clock.advanceBy(1_000); // повторы, тайм-ауты и переподключение без реального ожидания

Подробнее: руководство по testing.