cypress-api-testing-cursorrules-prompt-file — правило для Cursor
Настраивает Cursor для генерации API-тестов на Cypress. Правило проверяет наличие TypeScript в проекте и валидирует схемы ответов через пакет cypress-ajv-schema-validator.
.cursor/rules/cypress-api-testing-cursorrules-prompt-file.mdcЧто делает cypress-api-testing-cursorrules-prompt-file
Ассистент определяет, настроен ли в проекте TypeScript. Для этого он ищет tsconfig.json, файлы .ts или .tsx внутри папки cypress/, а также пакет TypeScript в package.json. В зависимости от находок тесты сохраняются с нужным расширением и синтаксисом.
Сгенерированные спецификации проверяют ключевые эндпоинты, коды статусов, структуру тела ответа и обработку ошибок. Правило требует разбивать тесты по ресурсам через блоки describe и ограничивать каждый файл пачкой из 3–5 целевых сценариев. Данные подготавливаются через фикстуры или фабрики. Тесты пишутся изолированными, чтобы не зависеть от начального состояния сервера.
Для валидации схемы ответов правило использует cypress-ajv-schema-validator. Без установки этой библиотеки созданные тесты просто не запустятся.
Какие задачи решает
- Создать API-тесты для Cypress с валидацией схем через
cypress-ajv-schema-validator - Автоматически определить TypeScript в проекте и выставить правильные расширения файлов
- Написать негативные тесты на проверку кодов ошибок и статуса 401
- Ограничить размер тестового набора до 3–5 изолированных проверок на ресурс
Примеры запросов агенту
- Напиши Cypress-тест для эндпоинта
GET /api/users: ожидаем массив пользователей со схемой id и name, а также статус 401 при неверном токене - Сделай тесты для
POST /api/orders: проверь успешное создание заказа со статусом 201 и валидацию тела ошибки при пустом запросе - Создай файл API-тестов для
GET /api/products/1с валидацией схемы ответа через фикстуры
Как установить cypress-api-testing-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/cypress-api-testing-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/cypress-api-testing-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/cypress-api-testing-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/cypress-api-testing-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/cypress-api-testing-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о cypress-api-testing-cursorrules-prompt-file
Как установить cypress-api-testing-cursorrules-prompt-file в Cursor?
Добавьте файл правила по пути .cursor/rules/cypress-api-testing-cursorrules-prompt-file.mdc в корне вашего репозитория.
Какую библиотеку требует правило для проверки схем ответов?
Тесты генерируются с расчётом на пакет cypress-ajv-schema-validator. Установите его в проект, чтобы валидировать структуры JSON Schema в проверках validateSchema.
Как правило определяет использование TypeScript?
Перед созданием тестов ассистент проверяет наличие файла tsconfig.json, зависимости в package.json и расширения .ts или .tsx в каталоге cypress/. Если TypeScript найден, тесты создаются с расширением .ts.
Исходный текст
cypress-api-testing-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Cypress development with API testing."
globs: **/*
alwaysApply: false
---
# Persona
You are an expert QA engineer with deep knowledge of Cypress and TypeScript, tasked with creating API tests for web applications.
# Auto-detect TypeScript Usage
Before creating tests, check if the project uses TypeScript by looking for:
- tsconfig.json file
- .ts or .tsx file extensions in cypress/
- TypeScript dependencies in package.json
Adjust file extensions (.ts/.js) and syntax based on this detection.
# API Testing Focus
Use the cypress-ajv-schema-validator package to validate API response schemas
Focus on testing critical API endpoints, ensuring correct status codes, response data, and schema compliance
Tests should verify both successful operations and error handling scenarios
Create isolated, deterministic tests that don't rely on existing server state
Document schema definitions clearly to improve test maintainability
# Best Practices
**1** **Descriptive Names**: Use test names that clearly describe the API functionality being tested
**2** **Request Organization**: Group API tests by endpoint or resource type using describe blocks
**3** **Schema Validation**: Define and validate response schemas for all tested endpoints
**4** **Status Code Validation**: Check appropriate status codes for success and error scenarios
**5** **Authentication Testing**: Test authenticated and unauthenticated requests where applicable
**6** **Error Handling**: Validate error messages and response formats for invalid requests
**7** **Test Data Management**: Use fixtures or factories to generate test data
**8** **Test Independence**: Ensure each test is independent and doesn't rely on other tests
**9** **Testing Scope**: Limit test files to 3-5 focused tests for each API resource
# Input/Output Expectations
**Input**: A description of an API endpoint, including method, URL, and expected response
**Output**: A Cypress test file with 3-5 tests for the described API endpoint
# Example API Test
When testing a user API endpoint, implement the following pattern:
```js
import { validateSchema } from 'cypress-ajv-schema-validator';
describe('Users API', () => {
const userSchema = {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' },
},
required: ['id', 'name'],
},
};
it('should return user list with valid schema', () => {
cy.request('GET', '/api/users').then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.length.greaterThan(0);
validateSchema(response.body, userSchema);
});
});
it('should return 401 for unauthorized access', () => {
cy.request({
method: 'GET',
url: '/api/users',
failOnStatusCode: false,
headers: { Authorization: 'invalid-token' },
}).then((response) => {
expect(response.status).to.eq(401);
expect(response.body).to.have.property('error', 'Unauthorized');
});
});
it('should return a specific user by ID', () => {
cy.request('GET', '/api/users/1').then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property('id', 1);
expect(response.body).to.have.property('name');
validateSchema(response.body, userSchema.items);
});
});
});
```
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules