testing

Используйте при написании или запуске тестов для этого проекта. Охватывает решения по выбору между модульными и E2E-тестами, расположение тестовых файлов, шаблоны моков и специфические для проекта методы тестирования…

npx skills add https://github.com/cloudflare/sandbox-sdk --skill testing

Testing in Sandbox SDK

This skill covers project-specific testing conventions. For TDD methodology, use the superpowers:test-driven-development skill.

Two Test Suites

Unit Tests

When to use: Testing isolated logic, client behavior, service methods, utilities.

Location:

  • SDK: packages/sandbox/tests/
  • Container: packages/sandbox-container/tests/

Runtime:

  • SDK tests run in Workers runtime via @cloudflare/vitest-pool-workers
  • Container tests run in Bun runtime

Commands:

npm test                              # All unit tests
npm test -w @cloudflare/sandbox       # SDK tests only
npm test -w @repo/sandbox-container   # Container tests only

Mock patterns:

  • SDK tests use a mock container (no Docker needed)
  • Container tests mock external dependencies (filesystem, processes)
  • Use createNoOpLogger() from @repo/shared for logger mocks

Known issue: SDK unit tests may hang on exit due to vitest-pool-workers workerd shutdown. Tests still pass/fail correctly - the hang is cosmetic.

E2E Tests

When to use: Testing full request flow, container integration, real Docker behavior.

Location: tests/e2e/

Runtime: Real Cloudflare Workers + Docker containers

Commands:

npm run test:e2e                                                           # All E2E tests (vitest + browser)
npm run test:e2e:vitest -- -- tests/e2e/process-lifecycle-workflow.test.ts # Single vitest file
npm run test:e2e:vitest -- -- tests/e2e/git-clone-workflow.test.ts -t 'test name'  # Single vitest test
npm run test:e2e:browser                                                   # Browser tests only (Playwright)

Note: Use test:e2e:vitest when filtering tests. The test:e2e wrapper doesn't support argument passthrough.

Key patterns:

  • All tests share ONE container for performance
  • Use unique sessions for test isolation
  • Tests run in parallel via thread pool
  • Config: vitest.e2e.config.ts (root level)

Writing E2E tests:

import { createTestSession } from './helpers';

describe('Feature X', () => {
  let session: TestSession;

  beforeEach(async () => {
    session = await createTestSession(); // Gets unique session
  });

  it('should do something', async () => {
    const result = await session.sandbox.exec('echo hello');
    expect(result.stdout).toBe('hello\n');
  });
});

When to Use Which

ScenarioTest Type
Client method logicUnit
Service business logicUnit
Request/response handlingUnit
Full command execution flowE2E
File operations with real filesystemE2E
Process lifecycle (start, stop, signal)E2E
Port exposure and preview URLsE2E
Git operationsE2E

Test-Specific Conventions

File naming: *.test.ts for both unit and E2E tests

Test structure:

describe('ComponentName', () => {
  describe('methodName', () => {
    it('should do X when Y', async () => {
      // Arrange
      // Act
      // Assert
    });
  });
});

Assertions: Use vitest's expect() with clear, specific assertions

Running Tests During Development

After making any meaningful code change:

  1. npm run check - catch type errors first
  2. npm test - verify unit tests pass
  3. npm run test:e2e - if touching core functionality

Build trust: The monorepo build system handles dependencies automatically. E2E tests always run against latest built code - no manual rebuild needed.

Больше skills от cloudflare

workerd-api-review
cloudflare
Оптимизация производительности, дизайн и совместимость API, уязвимости безопасности и соответствие стандартам для рецензирования кода workerd. Охватывает tcmalloc-совместимые…
official
workerd-safety-review
cloudflare
Паттерны безопасности памяти, потокобезопасности, конкурентности и критического обнаружения для ревью кода workerd. Охватывает граничные риски V8/KJ, управление временем жизни,…
official
module-registry
cloudflare
Загружать при работе с реестром модулей в workerd — чтение, изменение, отладка или проверка разрешения модулей, компиляции, оценки или регистрации…
official
reproduce
cloudflare
Воспроизвести проблему из репозитория cloudflare/agents на GitHub, создав минимальный проект Agents/Worker и развернув его на временном аккаунте Cloudflare, затем сообщить…
official
local-explorer
cloudflare
Как добавлять продукты/ресурсы в локальный обозреватель или локальный API. Используйте при реализации новых локальных API или маршрутов пользовательского интерфейса в…
official
commit-categories
cloudflare
Правила категоризации коммитов для журналов изменений и сводок «что нового». ДОЛЖНЫ быть загружены перед категоризацией коммитов в командах changelog или whats-new. Предоставляет…
official
architecture
cloudflare
Используйте при первом знакомстве с кодовой базой, добавлении нового метода клиента, добавлении нового обработчика/сервиса контейнера или понимании того, как проходит запрос…
official
changesets
cloudflare
Используется при создании changeset, подготовке релиза или обновлении версий. Охватывает, на какие пакеты ссылаться, как писать описания changeset для пользователей,…
official