graphql-yoga-tests
БесплатноБез исполняемых скриптовНе проверенUse whenever a GraphQL Yoga or Mercurius server needs tests: in-process yoga.fetch() for queries and mutations, executor-http for subscriptions and streaming…
от testland★ 18 звёзд на GitHubОб этом скилле
graphql-yoga-tests
Overview
Per
the-guild.dev/graphql/yoga-server/docs/features/testing:
"Calling the yoga.fetch method does not send an actual HTTP
request. It simulates the HTTP request which 100% conforms with
how Request/Response work."
Structurally different from Apollo's executeOperation - Yoga's
testing path goes through the HTTP transport layer including
middleware, headers, and response codes. There is no separate
"in-process" vs "HTTP-layer" choice.
When to use
- Unit / integration tests for a Yoga-based GraphQL server.
- Subscription tests (SSE / WS via Yoga).
- Production-config gates for Yoga's plugin-based controls.
Authoring
Install
npm install --save-dev graphql-yoga @graphql-tools/executor-http
Basic test
Per Yoga docs:
import { createYoga, createSchema } from 'graphql-yoga';
const yoga = createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query { greetings: String }
`,
resolvers: { Query: { greetings: () => 'Hello' } },
}),
});
test('greetings', async () => {
const response = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{ greetings }' }),
});
const result = await response.json();
expect(result.data.greetings).toBe('Hello');
});
The URL http://yoga/graphql is a placeholder - yoga.fetch
doesn't make a network call, but the URL must parse.
HTTP executor for subscriptions
Per Yoga docs:
import { buildHTTPExecutor } from '@graphql-tools/executor-http';
import { parse } from 'graphql';
const executor = buildHTTPExecutor({ fetch: yoga.fetch });
const result = await executor({ document: parse(`{ greetings }`) });
expect(result.data.greetings).toBe('Hello');
For subscriptions (SSE):
const stream = await executor({ document: parse(subscriptionQuery) });
if (Symbol.asyncIterator in stream) {
for await (const event of stream) {
expect(event.data).toBeDefined();
if (allEventsReceived) break;
}
}
Auth header pass-through
const response = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${testToken}`,
},
body: JSON.stringify({ query: '{ me { id } }' }),
});
Yoga's context-builder runs against the simulated request, so auth middleware is exercised.
Worked example
Integration scenario combining the operations above in one file: verify a
{ me { id } } query requires a bearer token, and that introspection is off in
the production plugin set.
- Build the server with
createYoga({ schema, plugins: [useDisableIntrospection()] })and a context-builder that readsAuthorization. yoga.fetch{ me { id } }with no header; parse.json()and assertresult.errorsis present - the context / auth middleware rejected it.yoga.fetchthe same query withAuthorization: Bearer ${testToken}; assertresult.data.me.idis returned.yoga.fetchan{ __schema { types { name } } }query; assertresult.errors[0].messagematches/introspection/i.
Result: one file proves auth pass-through (tokenless rejected, valid token resolves) and the production introspection gate in-process, no network.
Running
Standard test commands
npm test
Production-config tests
Yoga's production gates - disable-introspection and persisted-operations - have their own plugin setup and strict-mode assertions. Full test patterns are in references/production-config-tests.md.
Parsing results
yoga.fetch returns a standard Response. Parse with .json()
for non-streaming queries; iterate with the async-iterator for
subscriptions.
The response shape:
{
"data": { "greetings": "Hello" },
"errors": [
{
"message": "...",
"path": ["greetings"],
"extensions": { "code": "..." }
}
]
}
Yoga uses useMaskedErrors by default (per Yoga docs) - error
messages are masked to "Unexpected error" in production unless
the error has been marked safe. Test against this:
const resp = await yoga.fetch(/* ... */);
const result = await resp.json();
// Production: error message is "Unexpected error", original
// hidden in extensions if at all
expect(result.errors[0].message).toBe('Unexpected error.');
CI integration
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with: { node-version: '20' }
- run: npm ci
- run: npm test
- name: Production-mode tests
env: { NODE_ENV: production }
run: npx jest tests/production-config/
Anti-patterns
| Anti-pattern | Why it fails | Fix |
|---|---|---|
| Skipping `yoga.fe |
Установить graphql-yoga-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл graphql-yoga-tests?
Use whenever a GraphQL Yoga or Mercurius server needs tests: in-process yoga.fetch() for queries and mutations, executor-http for subscriptions and streaming, auth headers, and checks for disabled introspection and persisted operations. Mercurius app.inject() patterns are in its references.
Как установить скилл graphql-yoga-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл graphql-yoga-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic