playground-msw-tests
БесплатноБез исполняемых скриптовНе проверенREQUIRED and PRIMARY testing approach for packages/playground and packages/playground-ui. Triggers on: adding or modifying hooks, pages, route components…
от mastra-ai★ 29 944 звезды на GitHubОб этом скилле
MSW + client-js Fixtures: Primary Testing Strategy
Core Principle
Drive the real transport, mock the network.
Tests in packages/playground and packages/playground-ui MUST be written as
Vitest tests that exercise the real @mastra/client-js SDK, the real React Query
cache, and the real component/hook code paths. The only seam we mock is the
network boundary, via MSW.
This catches contract drift between the playground and @mastra/client-js at
typecheck time and at test time — something vi.mock('@/hooks/...') style tests
cannot do.
Priority Order
When you write or refactor a test for these packages, choose in this order:
- MSW + typed client-js fixtures (THIS SKILL) — for hooks, pages, routes, data-fetching, gating, redirect logic, query/mutation flows, error paths.
- Playwright E2E (
e2e-tests-studioskill) — only for genuine cross-page user journeys, real browser concerns (focus/keyboard/viewport), or anything that requires a real running Mastra server. - Pure unit tests — only for self-contained utilities/services with no network, no React Query, no router involvement.
If the same behavior can be covered by both #1 and #2, prefer #1. MSW tests are faster, deterministic, run in CI without browsers, and assert the real wire contract.
What NOT to do
- ❌
vi.mock('@/domains/.../hooks/use-agents')— mocking our own hooks hides cache, gating and transport bugs. - ❌ Implementation-mirror tests — do not duplicate source class strings, branch logic, generated shapes, or calculations without asserting a real behavior or regression.
- ❌ Class-name-only visual tests —
expect(node.className).toContain(...)usually just tests that the implementation string exists. Prefer no test over a className duplication test; use computed style, user-visible behavior, or a browser/Storybook check unless the class string itself is the public API. - ❌ Inline TypeScript types in tests (
type AgentLite = { id: string }) — these drift silently from the real SDK. - ❌
as any/as unknown as ListAgentsResponseon fixture data, MSW responses, request payloads, hook inputs, or component event inputs. - ❌ Returning bespoke shapes from MSW handlers that don't match the real
@mastra/client-jsresponse. If a field is optional, include it as optional in the fixture, don't omit the type.
What TO do
- ✅ Put fixtures in a
__tests__/fixtures/folder next to the test file. - ✅ Type every fixture with a response type re-exported from
@mastra/client-js(e.g.ListStoredAgentsResponse,GetAgentResponse,BuilderSettingsResponse,GetToolResponse,GetWorkflowResponse,ListStoredSkillsResponse). - ✅ Use direct imports and inferred types from real SDK, hook, component, DOM, or Testing Library APIs for MSW payloads, request payloads, hook inputs, and component events.
- ✅ Register MSW handlers per test with
server.use(...)so handlers reset between tests via the globalafterEach. - ✅ Render through
MastraReactProvider+QueryClientProvider+MemoryRouterso the real client SDK is the transport. - ✅ Use
vi.fn()wrappers inside MSW handlers to assert which endpoints were hit (great for testingenabled: ...gating without mocking hooks).
Standard Test Skeleton
// @vitest-environment jsdom
import { MastraReactProvider } from '@mastra/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { MemoryRouter } from 'react-router';
import { afterEach, describe, expect, it } from 'vitest';
import { server } from '@/test/msw-server';
import { Subject } from '../subject';
import { happyPathResponse } from './fixtures/subject';
const BASE_URL = 'http://localhost:4111';
const renderSubject = () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MastraReactProvider baseUrl={BASE_URL}>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<Subject />
</MemoryRouter>
</QueryClientProvider>
</MastraReactProvider>,
);
};
afterEach(() => cleanup());
describe('Subject', () => {
it('renders the happy path', async () => {
server.use(http.get(`${BASE_URL}/api/agents`, () => HttpResponse.json(happyPathResponse)));
renderSubject();
expect(await screen.findByText('Expected behavior')).not.toBeNull();
});
});
Standard Fixture File
// packages/playground/src/.../__tests__/fixtures/subject.ts
import type { ListStoredAgentsResponse } from '@mastra/client-js';
export const emptyStoredAgents: ListStoredAgentsResponse = {
agents: [],
total: 0,
page: 1,
perPage: 50,
hasMore: false,
};
export const oneDraftAgent: ListStoredAgentsResponse = {
...emptyStoredAgents,
agents: [
{
id: 'agent-1',
name: 'Draft Age
Установить playground-msw-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл playground-msw-tests?
REQUIRED and PRIMARY testing approach for packages/playground and packages/playground-ui. Triggers on: adding or modifying hooks, pages, route components, data-fetching code, React Query interactions, or any test work in these packages. Generates Vitest tests that drive the real @mastra/client-js + React Query stack through MSW handlers and typed fixtures derived from @mastra/client-js response types. This is the #1 way to test the playground packages — ABOVE Playwright E2E. Use Playwright only for cross-page user journeys that MSW cannot model.
Как установить скилл playground-msw-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл playground-msw-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic