Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

testing

БесплатноБез исполняемых скриптовНе проверен

Writing tests for the B2C CLI project using Mocha, Chai, and MSW. Use when writing unit or integration tests, mocking HTTP requests with MSW, testing CLI…

SalesforceCommerceCloudот SalesforceCommerceCloud★ 58 звёзд на GitHub17 установок в других каталогах

Об этом скилле

Testing

This skill covers project-specific testing patterns for the B2C CLI project.

Test Framework Stack

  • Test Runner: Mocha
  • Assertions: Chai (property-based)
  • HTTP Mocking: MSW (Mock Service Worker)
  • Stubbing/Mocking: Sinon
  • Code Coverage: c8
  • TypeScript: tsx (native execution without compilation)

Running Tests

For coding agents (minimal output - only failures shown):

# Run tests - only failures + summary
pnpm run test:agent

# Run tests for specific package
pnpm --filter @salesforce/b2c-tooling-sdk run test:agent
pnpm --filter @salesforce/b2c-cli run test:agent

For debugging (full output with coverage):

# Run all tests with coverage
pnpm run test

# Run tests for specific package
pnpm --filter @salesforce/b2c-tooling-sdk run test
pnpm --filter @salesforce/b2c-cli run test

# Run single test file (no coverage, faster)
cd packages/b2c-tooling-sdk
pnpm mocha "test/clients/webdav.test.ts"

# Run tests matching pattern
pnpm mocha --grep "mkcol" "test/**/*.test.ts"

# Watch mode for TDD
pnpm --filter @salesforce/b2c-tooling-sdk run test:watch

Test Organization

Tests mirror the source directory structure with .test.ts suffix:

packages/b2c-tooling-sdk/
├── src/
│   └── clients/
│       └── webdav.ts
└── test/
    └── clients/
        └── webdav.test.ts

Import Patterns

Always use package exports, not relative paths:

// Good - uses package exports
import { WebDavClient } from '@salesforce/b2c-tooling-sdk/clients';
import { OAuthStrategy } from '@salesforce/b2c-tooling-sdk/auth';

// Avoid - relative paths
import { WebDavClient } from '../../src/clients/webdav.js';

This ensures tests use the same export paths as consumers.

Config Isolation

Tests that check for "missing credentials" or "no config" scenarios need isolation from the developer's real configuration files (~/.mobify, dw.json) and environment variables.

Using Config Isolation Helpers

import { isolateConfig, restoreConfig } from '../helpers/config-isolation.js';

describe('config-dependent tests', () => {
  beforeEach(() => {
    isolateConfig();
  });

  afterEach(() => {
    restoreConfig();
  });

  it('handles missing credentials', async () => {
    // Test now runs without reading real ~/.mobify or SFCC_* env vars
  });
});

The helpers:

  • Clear all SFCC_* and MRT_* environment variables
  • Clear other config-affecting vars (LANGUAGE, NO_COLOR)
  • Must call restoreConfig() in afterEach to restore original state

For SDK Unit Tests (bypass config sources)

When testing resolveConfig directly without file system:

import { resolveConfig } from '@salesforce/b2c-tooling-sdk/config';

const config = resolveConfig({}, {
  replaceDefaultSources: true,
  sources: []  // No file-based sources
});

For MRT Credential Isolation

Use the credentialsFile option to override the default ~/.mobify path:

import { resolveConfig } from '@salesforce/b2c-tooling-sdk/config';

// Point to non-existent file for isolation
const config = resolveConfig({}, {
  credentialsFile: '/dev/null'
});

In CLI command tests, use the stubParse helper with the credentials-file flag:

import { stubParse } from '../helpers/stub-parse.js';

stubParse(command, {'credentials-file': '/dev/null'});  // Isolates from real ~/.mobify

Polling Tests (Avoid Fake Timers)

Do not use fake timers with MSW. MSW v2 uses microtasks internally, and fake timers prevent MSW's promises from resolving.

Instead, use the pollInterval option for fast tests:

// Good - use short poll interval
const result = await siteArchiveImport(mockInstance, siteDir, {
  archiveName: 'test-import',
  waitOptions: { pollInterval: 10 }  // 10ms instead of default 3000ms
});

// Bad - fake timers break MSW
import FakeTimers from '@sinonjs/fake-timers';
const clock = FakeTimers.install();  // DON'T DO THIS with MSW

HTTP Mocking with MSW

Basic Setup

import { expect } from 'chai';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { WebDavClient } from '@salesforce/b2c-tooling-sdk/clients';
import { MockAuthStrategy } from '../helpers/mock-auth.js';

const TEST_HOST = 'test.salesforce.com';
const BASE_URL = `https://${TEST_HOST}`;

const server = setupServer();

describe('WebDavClient', () => {
  let client: WebDavClient;
  let mockAuth: MockAuthStrategy;

  before(() => {
    server.listen({ onUnhandledRequest: 'error' });
  });

  afterEach(() => {
    server.resetHandlers();
  });

  after(() => {
    server.close();
  });

  beforeEach(() => {
    mockAuth = new MockAuthStrategy();
    client = new WebDavClient(TEST_HOST, mockAuth);
  });

  it('creates a directory successfully', async () => {
    server.use(
      http.all(`${BASE_URL}/*`, ({ request }) => {
        if (request.method === 'MKCOL') {
          return new
Полный SKILL.md на GitHub

Установить testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/CLI-COMMAND-TESTING.mdreferences/COMMAND-TESTING-PATTERNS.mdreferences/HELPERS.md

FAQ

Что делает скилл testing?

Writing tests for the B2C CLI project using Mocha, Chai, and MSW. Use when writing unit or integration tests, mocking HTTP requests with MSW, testing CLI commands with oclif, isolating config in tests, setting up test coverage, using sinon stubs, c8 coverage, capturing or silencing stdout, or creating MSW handlers.

Как установить скилл testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить testing с