mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+265
-137
@@ -1,151 +1,279 @@
|
||||
---
|
||||
description: This rule enforces best practices and coding standards for Playwright tests, including stable selectors, test isolation, user-centric testing, and performance considerations.
|
||||
globs: *.spec.ts
|
||||
description: Definitive guidelines for writing robust, maintainable, and high-quality end-to-end tests with Playwright in TypeScript.
|
||||
globs: **/*.{js,ts}
|
||||
---
|
||||
- **General Principles**
|
||||
- **Test User-Visible Behavior:** Focus tests on how users interact with your application, not on internal implementation details.
|
||||
- **Isolate Tests:** Ensure tests are independent of each other to prevent cascading failures and ensure predictable results.
|
||||
- **Avoid Testing Third-Party Dependencies:** Mock or stub external services and APIs to isolate your application's behavior.
|
||||
# Playwright Best Practices
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Directory Structure:**
|
||||
- `tests/`: Contains all test files.
|
||||
- `tests/e2e/`: End-to-end tests.
|
||||
- `tests/unit/`: Unit tests (if applicable, though Playwright is primarily for E2E).
|
||||
- `tests/utils/`: Helper functions and page object models.
|
||||
- **File Naming Conventions:**
|
||||
- Use `.spec.ts` or `.spec.js` for test files (e.g., `login.spec.ts`).
|
||||
- Group related tests in the same file.
|
||||
- **Module Organization:**
|
||||
- Employ Page Object Model (POM) to encapsulate UI elements and interactions.
|
||||
- **Component Architecture:**
|
||||
- Structure tests around components or features of your application.
|
||||
- **Code Splitting Strategies:**
|
||||
- Not directly applicable to tests, but keep test files concise and focused.
|
||||
Playwright is the gold standard for reliable E2E testing. These rules ensure your tests are fast, stable, and easy to maintain, aligning with modern 2025 development standards for reliability, quality, and structure.
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
- **Design Patterns:**
|
||||
- **Page Object Model (POM):** A common pattern where each page is represented as a class, with methods for interacting with the page's elements. This improves reusability and maintainability. Example:
|
||||
typescript
|
||||
class LoginPage {
|
||||
constructor(private readonly page: Page) {}
|
||||
## 1. Always Use `@playwright/test`
|
||||
|
||||
async goto() {
|
||||
await this.page.goto('/login');
|
||||
}
|
||||
Leverage the official test runner for built-in fixtures, isolation, and web-first assertions. Avoid the low-level `playwright` library for E2E tests.
|
||||
|
||||
async login(username: string, password: string) {
|
||||
await this.page.fill('#username', username);
|
||||
await this.page.fill('#password', password);
|
||||
await this.page.click('#login-button');
|
||||
}
|
||||
❌ BAD: Using `playwright` directly
|
||||
```typescript
|
||||
import { chromium } from 'playwright';
|
||||
// ... manual browser/context setup and teardown
|
||||
const browser = await chromium.launch();
|
||||
const page = await browser.newPage();
|
||||
// ...
|
||||
await browser.close();
|
||||
```
|
||||
|
||||
async getErrorMessage() {
|
||||
return await this.page.textContent('#error-message');
|
||||
}
|
||||
}
|
||||
|
||||
- **Fixture pattern:** Use Playwright's built-in fixtures to manage test setup and teardown. This ensures each test starts in a clean state.
|
||||
- **Recommended Approaches:**
|
||||
- Use `baseURL` in `playwright.config.ts` to avoid hardcoding URLs in tests.
|
||||
- Utilize `expect` matchers for assertions (e.g., `expect(page.locator('#success')).toBeVisible()`).
|
||||
- Use auto-waiting features for improved stability.
|
||||
- **Anti-patterns:**
|
||||
- Hardcoding URLs.
|
||||
- Using brittle selectors (e.g., XPath based on DOM structure).
|
||||
- Writing tests that depend on each other.
|
||||
- **State Management:**
|
||||
- Keep tests stateless. Reset the application state before each test.
|
||||
- Use database transactions or API calls to seed data for tests.
|
||||
- **Error Handling:**
|
||||
- Use `try...catch` blocks to handle expected errors.
|
||||
- Log errors and failures with descriptive messages.
|
||||
- Use `expect.soft()` for non-critical assertions that shouldn't fail the test immediately.
|
||||
✅ GOOD: Using `@playwright/test`
|
||||
```typescript
|
||||
import { test, expect } from '@playwright/test';
|
||||
test('should navigate to home', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await expect(page).toHaveTitle(/Home/);
|
||||
});
|
||||
```
|
||||
|
||||
- **Performance Considerations**
|
||||
- **Optimization Techniques:**
|
||||
- Run tests in parallel to reduce overall test execution time.
|
||||
- Use `reuseExistingServer: true` in `playwright.config.ts` during development to speed up debugging.
|
||||
- Use `codegen` to generate selectors automatically.
|
||||
- **Memory Management:**
|
||||
- Close pages and browsers after each test or group of tests to release resources.
|
||||
- **Rendering Optimization:**
|
||||
- Not directly applicable but optimize your application's rendering for faster testing.
|
||||
- **Bundle Size Optimization:**
|
||||
- Not directly applicable, but optimize your application's bundle size for faster loading.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Not directly applicable to tests.
|
||||
## 2. Prioritize Robust Locators
|
||||
|
||||
- **Security Best Practices**
|
||||
- **Common Vulnerabilities:**
|
||||
- Avoid exposing sensitive data (e.g., passwords, API keys) in test code or logs.
|
||||
- **Input Validation:**
|
||||
- Test input validation to ensure your application handles invalid data correctly.
|
||||
- **Authentication and Authorization:**
|
||||
- Test different user roles and permissions.
|
||||
- **Data Protection:**
|
||||
- Ensure sensitive data is encrypted in the database.
|
||||
- **Secure API Communication:**
|
||||
- Test that API calls are made over HTTPS.
|
||||
Use Playwright's built-in Locators API, favoring user-facing attributes over brittle CSS selectors. This drastically improves test stability.
|
||||
|
||||
- **Testing Approaches**
|
||||
- **Unit Testing:**
|
||||
- While Playwright primarily focuses on E2E testing, unit tests can be written for utility functions or components.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different parts of your application.
|
||||
- **End-to-End Testing:**
|
||||
- Simulate user flows to test the entire application.
|
||||
- **Test Organization:**
|
||||
- Group tests by feature or functionality.
|
||||
- Use `describe` blocks to organize tests.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use Playwright's `route` API to mock API responses.
|
||||
- Use `locator.evaluate` to stub JavaScript functions.
|
||||
❌ BAD: Fragile, implementation-dependent selectors
|
||||
```typescript
|
||||
await page.locator('div.container > ul > li:nth-child(2) > button').click();
|
||||
```
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **Frequent Mistakes:**
|
||||
- Using XPath instead of CSS selectors.
|
||||
- Not using auto-waiting features.
|
||||
- Writing flaky tests.
|
||||
- **Edge Cases:**
|
||||
- Handling different screen sizes and devices.
|
||||
- Testing error conditions and edge cases.
|
||||
- **Version-Specific Issues:**
|
||||
- Stay up-to-date with Playwright's release notes and upgrade guides.
|
||||
- **Compatibility Concerns:**
|
||||
- Test on different browsers and operating systems.
|
||||
- **Debugging Strategies:**
|
||||
- Use Playwright Inspector to debug tests visually.
|
||||
- Use `console.log` statements to log information during test execution.
|
||||
- Use `pause()` to halt test execution and inspect the page.
|
||||
✅ GOOD: Semantic, user-facing locators
|
||||
```typescript
|
||||
await page.getByRole('button', { name: 'Add to Cart' }).click();
|
||||
await page.getByLabel('Username').fill('testuser');
|
||||
await page.getByTestId('product-item-123').click();
|
||||
```
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Recommended Development Tools:**
|
||||
- VS Code with the Playwright extension.
|
||||
- **Build Configuration:**
|
||||
- Use TypeScript for type safety and autocompletion.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce code style.
|
||||
- **Deployment Best Practices:**
|
||||
- Run tests in CI/CD pipeline before deploying to production.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate Playwright with CI/CD tools like GitHub Actions, Jenkins, or GitLab CI.
|
||||
## 3. Embrace Web-First Assertions
|
||||
|
||||
- **Specific Best Practices & Details**
|
||||
- **Stable Selectors:** Prefer CSS selectors based on attributes like `data-testid` or `data-test-id` over XPath or fragile CSS classnames.
|
||||
- **Leverage Auto-waiting:** Playwright automatically waits for elements to be actionable before performing actions. Avoid explicit waits where possible. However, use explicit waits (e.g. `waitForSelector`) when necessary.
|
||||
- **Web-First Assertions:** Use `expect` assertions, which retry and wait for conditions to be met. They help to avoid flakiness.
|
||||
- **Configure Debugging Highlights:** Configure `playwright.config.ts` to highlight actions performed by playwright in the browser during debugging to see what's happening step by step. Example:
|
||||
typescript
|
||||
use: {
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
video: 'on',
|
||||
screenshot: 'only-on-failure',
|
||||
}
|
||||
|
||||
Playwright's `expect` assertions automatically retry until conditions are met, eliminating manual waits and flakiness. Never use `page.waitForTimeout()`.
|
||||
|
||||
- **Additional Notes**
|
||||
- Regularly review and update your test suite to reflect changes in your application.
|
||||
- Document your tests to make them easier to understand and maintain.
|
||||
- Use a consistent naming convention for your tests.
|
||||
❌ BAD: Manual, flaky waits and generic assertions
|
||||
```typescript
|
||||
await page.waitForTimeout(2000); // 🚨 Flaky!
|
||||
const title = await page.title();
|
||||
assert.equal(title, 'My Page'); // 🚨 Not web-first
|
||||
```
|
||||
|
||||
✅ GOOD: Reliable, auto-retrying assertions
|
||||
```typescript
|
||||
await expect(page).toHaveTitle(/My Page/);
|
||||
await expect(page.getByText('Welcome')).toBeVisible();
|
||||
await expect(page.getByRole('checkbox')).toBeChecked();
|
||||
```
|
||||
|
||||
## 4. Implement the Page Object Model (POM)
|
||||
|
||||
Encapsulate selectors and actions within dedicated classes. This improves readability, reusability, and maintainability.
|
||||
|
||||
❌ BAD: Repeated selectors and logic across tests
|
||||
```typescript
|
||||
// test-login.spec.ts
|
||||
await page.getByLabel('Username').fill('user');
|
||||
await page.getByLabel('Password').fill('pass');
|
||||
await page.getByRole('button', { name: 'Login' }).click();
|
||||
|
||||
// test-profile.spec.ts
|
||||
// ... same login steps repeated ...
|
||||
```
|
||||
|
||||
✅ GOOD: Centralized Page Object
|
||||
```typescript
|
||||
// pages/LoginPage.ts
|
||||
import { Page, Locator } from '@playwright/test';
|
||||
|
||||
export class LoginPage {
|
||||
readonly page: Page;
|
||||
readonly usernameInput: Locator;
|
||||
readonly passwordInput: Locator;
|
||||
readonly loginButton: Locator;
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page;
|
||||
this.usernameInput = page.getByLabel('Username');
|
||||
this.passwordInput = page.getByLabel('Password');
|
||||
this.loginButton = page.getByRole('button', { name: 'Login' });
|
||||
}
|
||||
|
||||
async navigate() {
|
||||
await this.page.goto('/login');
|
||||
}
|
||||
|
||||
async login(username: string, password: string) {
|
||||
await this.usernameInput.fill(username);
|
||||
await this.passwordInput.fill(password);
|
||||
await this.loginButton.click();
|
||||
}
|
||||
}
|
||||
|
||||
// tests/login.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { LoginPage } from '../pages/LoginPage';
|
||||
|
||||
test('should successfully log in', async ({ page }) => {
|
||||
const loginPage = new LoginPage(page);
|
||||
await loginPage.navigate();
|
||||
await loginPage.login('testuser', 'password');
|
||||
await expect(page).toHaveURL(/dashboard/);
|
||||
});
|
||||
```
|
||||
|
||||
## 5. Optimize Performance with Auth State & Route Blocking
|
||||
|
||||
Reduce test execution time by reusing authenticated sessions and blocking unnecessary network requests.
|
||||
|
||||
❌ BAD: Logging in for every test and loading all assets
|
||||
```typescript
|
||||
test('view profile', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('user');
|
||||
await page.getByLabel('Password').fill('pass');
|
||||
await page.getByRole('button', { name: 'Login' }).click();
|
||||
await page.goto('/profile'); // Loads all images, analytics, etc.
|
||||
});
|
||||
```
|
||||
|
||||
✅ GOOD: Reusing auth state and blocking requests
|
||||
```typescript
|
||||
// playwright.config.ts
|
||||
import { defineConfig } from '@playwright/test';
|
||||
export default defineConfig({
|
||||
use: {
|
||||
storageState: 'playwright-auth.json', // Path to save/load auth state
|
||||
},
|
||||
});
|
||||
|
||||
// global-setup.ts (run once before all tests)
|
||||
import { chromium, expect } from '@playwright/test';
|
||||
export default async function globalSetup() {
|
||||
const browser = await chromium.launch();
|
||||
const page = await browser.newPage();
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('testuser');
|
||||
await page.getByLabel('Password').fill('password');
|
||||
await page.getByRole('button', { name: 'Login' }).click();
|
||||
await expect(page).toHaveURL(/dashboard/);
|
||||
await page.context().storageState({ path: 'playwright-auth.json' });
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// tests/profile.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
test('should display user profile', async ({ page, context }) => {
|
||||
// Block unnecessary resources for faster tests
|
||||
await context.route('**/*.{png,jpg,jpeg,gif,webp,svg,css}', route => route.abort());
|
||||
await page.goto('/profile'); // Automatically uses saved auth state
|
||||
await expect(page.getByText('Welcome, testuser!')).toBeVisible();
|
||||
});
|
||||
```
|
||||
|
||||
## 6. Mock APIs for Deterministic Tests
|
||||
|
||||
Isolate your UI tests from backend flakiness by intercepting and mocking API responses.
|
||||
|
||||
❌ BAD: Relying on a live, potentially unstable backend
|
||||
```typescript
|
||||
test('display products', async ({ page }) => {
|
||||
await page.goto('/products'); // Fetches from real API
|
||||
await expect(page.getByText('Product A')).toBeVisible();
|
||||
});
|
||||
```
|
||||
|
||||
✅ GOOD: Mocking API responses
|
||||
```typescript
|
||||
test('display mocked products', async ({ page }) => {
|
||||
await page.route('**/api/products', route => {
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify([{ id: 1, name: 'Mock Product' }]),
|
||||
});
|
||||
});
|
||||
await page.goto('/products');
|
||||
await expect(page.getByText('Mock Product')).toBeVisible();
|
||||
});
|
||||
```
|
||||
|
||||
## 7. Leverage CI/CD Features for Debugging
|
||||
|
||||
Configure tracing, screenshots, and video recording in your `playwright.config.ts` to instantly diagnose failures in CI.
|
||||
|
||||
```typescript
|
||||
// playwright.config.ts
|
||||
import { defineConfig } from '@playwright/test';
|
||||
export default defineConfig({
|
||||
reporter: [['html'], ['list']],
|
||||
use: {
|
||||
trace: 'on-first-retry', // Record trace only on first retry
|
||||
screenshot: 'on', // Always take a screenshot on failure
|
||||
video: 'on-first-retry',// Record video on first retry
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## 8. Maintain Code Quality with Linters & Formatters
|
||||
|
||||
Integrate ESLint (with Playwright plugin) and Prettier into your workflow via pre-commit hooks to enforce consistent code style and catch errors early.
|
||||
|
||||
```json
|
||||
// package.json (example scripts)
|
||||
{
|
||||
"scripts": {
|
||||
"lint": "eslint . --ext .ts",
|
||||
"format": "prettier --write .",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.x.x",
|
||||
"@typescript-eslint/eslint-plugin": "^7.x.x",
|
||||
"@typescript-eslint/parser": "^7.x.x",
|
||||
"eslint": "^8.x.x",
|
||||
"eslint-plugin-playwright": "^1.x.x",
|
||||
"prettier": "^3.x.x",
|
||||
"husky": "^9.x.x",
|
||||
"lint-staged": "^15.x.x"
|
||||
}
|
||||
}
|
||||
```
|
||||
```javascript
|
||||
// .eslintrc.js
|
||||
module.exports = {
|
||||
root: true,
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['@typescript-eslint', 'playwright'],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:playwright/recommended',
|
||||
],
|
||||
rules: {
|
||||
// Add custom rules or override defaults here
|
||||
},
|
||||
env: {
|
||||
node: true,
|
||||
browser: true,
|
||||
},
|
||||
};
|
||||
```
|
||||
```json
|
||||
// .prettierrc
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
```
|
||||
```json
|
||||
// .husky/pre-commit
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npx lint-staged
|
||||
```
|
||||
```json
|
||||
// .lintstagedrc.js
|
||||
module.exports = {
|
||||
'*.{ts,js}': ['eslint --fix', 'prettier --write'],
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user