Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
@@ -0,0 +1,348 @@
---
description: This rule file provides guidelines for writing stable and maintainable end-to-end tests using Detox, covering code structure, testing strategies, and performance considerations. It includes best practices for test ID usage, dealing with flakiness, and integrating with CI/CD pipelines.
globs: **/*.{e2e.js,e2e.ts,spec.js,spec.ts}
---
# Detox E2E Testing Best Practices for React Native
This document outlines best practices for writing stable, maintainable, and performant end-to-end (E2E) tests for React Native applications using Detox.
## Ground Rules
- **Isolate Tests:** Each test should start fresh and not depend on the execution of previous tests. Restart the app before each test.
- **Consistent Input, Consistent Output:** Ensure identical app behavior across test iterations by managing varying server responses and app states. Mock server responses to prevent external variations.
- **End every test with an expectation:** Ensures a validation phase that confirms the intended outcome of the test.
## 1. Code Organization and Structure
### Directory Structure
<project_root>/
e2e/
config.js # Detox configuration file
utils.js # Helper functions for tests
firstTest.spec.js # Example test file
... # More test files
src/
... # Your application source code
- **`e2e` directory:** Dedicated directory for all Detox-related files.
- **`config.js`:** Contains Detox configuration, including device settings, build paths, and test runner configuration.
- **`utils.js` (or similar):** Houses reusable helper functions, such as custom matchers, navigation helpers, and data generation functions.
- **`*.spec.js` or `*.e2e.js`:** Test files containing the actual test cases. Choose a consistent naming convention.
### File Naming Conventions
- **Test files:** `[ComponentName].spec.js`, `[FeatureName].e2e.js`.
- **Helper functions:** `helpers.js`, `utils.js`, `testData.js`.
- **Configuration:** `detox.config.js` or `e2e.config.js`.
### Module Organization
- **Separate test logic from application code:** Tests reside in the `e2e` directory, separate from the `src` directory containing the app's source code.
- **Group related tests into modules:** For example, put all tests related to user authentication in an `e2e/auth/` directory.
- **Use helper modules:** Extract common test logic, like logging in a user or navigating to a specific screen, into reusable helper functions.
### Component Architecture (Page Object Model)
- **Implement the Page Object Model (POM):** Create classes or modules that represent UI screens or components. Each page object should encapsulate the selectors and actions for that screen.
javascript
// e2e/pageObjects/LoginPage.js
const { element, by, expect } = require('detox');
class LoginPage {
constructor() {
this.usernameField = element(by.id('username_input'));
this.passwordField = element(by.id('password_input'));
this.loginButton = element(by.id('login_button'));
}
async enterUsername(username) {
await this.usernameField.typeText(username);
}
async enterPassword(password) {
await this.passwordField.typeText(password);
}
async tapLoginButton() {
await this.loginButton.tap();
}
async isLoggedIn() {
await expect(element(by.id('home_screen'))).toBeVisible();
}
}
module.exports = new LoginPage();
- **Benefits of POM:**
- Improved test readability and maintainability.
- Reduced code duplication.
- Easier refactoring of UI elements.
### Code Splitting Strategies (Not directly applicable to Detox, but consider app bundle size)
- **Dynamic imports:** Utilize dynamic imports in the app code to load modules only when needed, improving initial load time. This is a React Native concern, not Detox itself, but Detox tests will execute faster on a faster-loading app.
- **Route-based splitting:** Split your app into separate bundles based on routes or features.
## 2. Common Patterns and Anti-patterns
### Design Patterns Specific to Detox
- **Wait for element to be visible:**
javascript
await waitFor(element(by.id('my_element'))).toBeVisible().withTimeout(5000);
- **Retry flaky tests:** Implement a retry mechanism for tests that occasionally fail due to timing issues or other unpredictable factors. Use Jest's retryTimes:
javascript
jest.retryTimes(3); // Retry the test up to 3 times
- **Use `beforeAll` and `beforeEach` wisely:** `beforeAll` is for setup that only needs to happen once for the entire test suite, while `beforeEach` is for setup that must be done before each test.
### Recommended Approaches for Common Tasks
- **Simulating user interactions:**
javascript
await element(by.id('my_button')).tap();
await element(by.id('my_input')).typeText('Hello, Detox!');
await element(by.id('my_scroll_view')).scroll(50, 'down');
- **Asserting element visibility and text content:**
javascript
await expect(element(by.id('my_element'))).toBeVisible();
await expect(element(by.text('Expected Text'))).toBeVisible();
await expect(element(by.id('my_element'))).toHaveText('Actual Text');
- **Handling alerts and dialogs:**
javascript
await expect(element(by.text('Alert Title'))).toBeVisible();
await element(by.text('OK')).tap(); // Dismiss the alert
### Anti-patterns and Code Smells to Avoid
- **Hardcoded timeouts:** Avoid using `setTimeout` directly. Rely on Detox's built-in synchronization and waiting mechanisms.
- **Incomplete Test Coverage:** Focus on critical paths and user flows, ensuring comprehensive coverage of the core functionalities.
- **Over-reliance on Thread.sleep() (or equivalent):** Try to use `waitFor` or Detox's synchronization primitives instead. Sleeping is almost always a sign that Detox's sync isn't working right.
- **Ignoring console.log statements:** Keep console log statements clean and helpful for debugging purposes.
### State Management Best Practices (App-level, impacts test environment)
- **Mock external dependencies:** Mock API calls, database interactions, and other external dependencies to ensure consistent test results and isolate the app's logic.
- **Control app state before each test:** Use `beforeEach` to reset the app's state to a known value before running each test. This can involve clearing data, logging out users, or navigating to a specific screen.
### Error Handling Patterns
- **Use `try...catch` blocks:** Wrap test actions in `try...catch` blocks to handle potential errors gracefully.
- **Log errors:** Log any errors that occur during test execution to help with debugging.
- **Fail tests on unexpected errors:** If a test encounters an unexpected error, mark the test as failed to prevent false positives.
## 3. Performance Considerations
### Optimization Techniques (Mainly React Native app optimization)
- **Minimize UI updates:** Reduce the number of UI updates during animations or interactions to improve rendering performance.
- **Use virtualization for long lists:** Virtualize long lists to render only the visible items, reducing memory consumption and improving scrolling performance. This improves the app's performance generally, leading to faster test execution.
- **Optimize image loading:** Optimize image sizes and use caching mechanisms to reduce image loading times.
### Memory Management (React Native app concern)
- **Release resources:** Properly release resources, such as event listeners and timers, when they are no longer needed to prevent memory leaks.
- **Use memoization:** Use memoization techniques to avoid recomputing expensive values when they haven't changed.
### Rendering Optimization (React Native app concern)
- **Use `shouldComponentUpdate` or `React.memo`:** Implement `shouldComponentUpdate` or `React.memo` to prevent unnecessary re-renders of components.
- **Avoid inline styles:** Avoid using inline styles, as they can cause performance issues.
### Bundle Size Optimization (React Native app concern)
- **Use code splitting:** Split your app into smaller chunks to reduce the initial bundle size.
- **Remove unused code:** Remove any unused code, such as dead code or unused libraries.
- **Optimize images:** Optimize image sizes and use appropriate image formats.
### Lazy Loading Strategies (React Native app concern)
- **Load components on demand:** Load components only when they are needed, such as when a user navigates to a specific screen.
- **Use lazy-loaded images:** Load images only when they are visible in the viewport.
## 4. Security Best Practices (App Security - Impacts Test Scope)
### Common Vulnerabilities and How to Prevent Them
- **Data injection:** Protect against data injection attacks by validating all user input and using parameterized queries.
- **Cross-site scripting (XSS):** Prevent XSS attacks by sanitizing all user-generated content before rendering it.
- **Man-in-the-middle (MITM) attacks:** Implement SSL/TLS to encrypt communication between the app and the server.
### Input Validation
- **Validate all user input:** Validate all user input on both the client and server sides to prevent invalid or malicious data from being processed.
- **Use appropriate validation libraries:** Use established validation libraries to simplify the validation process and ensure consistency.
### Authentication and Authorization Patterns
- **Use secure authentication protocols:** Use secure authentication protocols, such as OAuth 2.0 or OpenID Connect.
- **Implement proper authorization checks:** Implement proper authorization checks to ensure that users can only access the resources they are authorized to access.
### Data Protection Strategies
- **Encrypt sensitive data:** Encrypt sensitive data, such as passwords and credit card numbers, both in transit and at rest.
- **Store data securely:** Store data in secure locations, such as encrypted databases or keychains.
### Secure API Communication
- **Use HTTPS:** Always use HTTPS to encrypt communication between the app and the server.
- **Validate API responses:** Validate API responses to ensure that they are not tampered with.
## 5. Testing Approaches
### Unit Testing Strategies (Generally not used with Detox)
- **Test individual components or functions in isolation:** Use unit tests to verify the behavior of individual components or functions in isolation.
- **Use mocking to isolate dependencies:** Use mocking to isolate dependencies and ensure that the unit tests are not affected by external factors.
### Integration Testing
- **Test interactions between multiple components or modules:** Use integration tests to verify the interactions between multiple components or modules.
- **Use stubs to simulate external dependencies:** Use stubs to simulate external dependencies and ensure that the integration tests are not affected by real-world conditions.
### End-to-End Testing
- **Test the entire application from end to end:** Use end-to-end tests to verify the entire application flow from the user's perspective.
- **Simulate real user interactions:** Simulate real user interactions as closely as possible to ensure that the tests accurately reflect the user experience.
### Test Organization
- **Organize tests by feature or functionality:** Group tests by feature or functionality to improve test discoverability and maintainability.
- **Use descriptive test names:** Use descriptive test names to clearly indicate what each test is verifying.
- **Keep tests small and focused:** Keep tests small and focused on verifying a single aspect of the application.
### Mocking and Stubbing (Used sparingly with Detox. More common is configuring the backend)
- **Mock external dependencies:** Mock external dependencies, such as API calls or database interactions, to ensure consistent test results.
- **Use stubs to simulate specific scenarios:** Use stubs to simulate specific scenarios, such as error conditions or edge cases.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes Developers Make
- **Using brittle selectors:** Avoid using selectors that are based on text or position, as these can easily break when the UI changes. Use `testID` whenever possible.
- **Not handling asynchronous operations correctly:** Ensure that all asynchronous operations are properly handled to prevent race conditions and timing issues.
- **Ignoring error messages:** Pay attention to error messages and logs to identify and fix problems quickly.
### Edge Cases to Be Aware Of
- **Handling different screen sizes and orientations:** Test the app on different screen sizes and orientations to ensure that the UI adapts correctly.
- **Handling network connectivity issues:** Test the app's behavior when the network connection is slow or unavailable.
- **Handling different languages and locales:** Test the app with different languages and locales to ensure that it is properly localized.
### Version-Specific Issues
- **Keep Detox up to date:** Stay up to date with the latest version of Detox to take advantage of bug fixes and performance improvements.
- **Be aware of compatibility issues:** Be aware of compatibility issues between different versions of Detox, React Native, and other dependencies.
### Compatibility Concerns
- **Test on multiple devices and operating systems:** Test the app on a variety of devices and operating systems to ensure that it is compatible with the target audience.
- **Use a device farm:** Use a device farm, such as HeadSpin, to test the app on a wide range of real devices.
### Debugging Strategies
- **Use the Detox CLI:** Use the Detox CLI to run tests, inspect the app's state, and debug issues.
- **Use logging statements:** Use logging statements to track the execution flow and identify potential problems.
- **Use breakpoints:** Use breakpoints in your test code to pause execution and inspect variables.
## 7. Tooling and Environment
### Recommended Development Tools
- **Visual Studio Code:** A popular code editor with excellent support for JavaScript and React Native.
- **Detox CLI:** The Detox command-line interface for running tests and managing the Detox environment.
- **HeadSpin:** For running tests on real devices and analyzing performance metrics.
### Build Configuration
- **Configure Detox in `package.json`:** Configure Detox in the `package.json` file, including device settings, build paths, and test runner configuration.
- **Use different configurations for different environments:** Use different configurations for development, staging, and production environments.
### Linting and Formatting
- **Use ESLint:** Use ESLint to enforce code style and detect potential errors.
- **Use Prettier:** Use Prettier to automatically format code.
### Deployment Best Practices
- **Automate the deployment process:** Automate the deployment process using tools like Fastlane or Bitrise.
- **Use continuous integration and continuous delivery (CI/CD):** Use CI/CD to automatically build, test, and deploy the app whenever changes are made.
### CI/CD Integration
- **Integrate Detox tests into your CI/CD pipeline:** Integrate Detox tests into your CI/CD pipeline to automatically run tests whenever changes are made.
- **Use a CI/CD service like Jenkins, CircleCI, or Travis CI:** Use a CI/CD service like Jenkins, CircleCI, or Travis CI to automate the build, test, and deployment process.
## Working with Test IDs
### Benefits of Test IDs
* Stable matchers that don't depend on UI text.
* Locale-agnostic testing.
* Clear code navigability.
### Assigning Test IDs
* **React Native:** Use the `testID` prop on View components.
jsx
<View>
<TouchableOpacity testID="Onboarding.Next_button">
<Text>Next</Text>
</TouchableOpacity>
</View>
* **iOS Native:** Use the `accessibilityIdentifier` property.
* **Android Native:** Use the `viewTag` property.
### Best Practices for Naming Test IDs
* Use a consistent naming system (e.g., `ITEM_NAME_ALL_CAPS` or `ItemNameUpperCamelCase`).
* Use notations for special items (e.g., `_ROOT` for screen roots, `_BTN` for buttons).
* Apply consistent prefixes as categories (e.g., `EDIT_PROFILE_SCREEN.DONE_BTN`).
* Drill down to details of elements via chains of contexts (e.g., `SITE_LIST_ITEM1.OPTIONS`).
* In large projects, use module identifiers (e.g., `AUTH.LOGIN_SCREEN.EDIT_PASSWORD`).
#### Examples of good test ID usage:
EDIT_PROFILE_SCREEN.DONE_BTN
SITE_LIST_ROOT
SITE_LIST_ITEM1.OPTIONS
### Rules of Thumb for test IDs
* Use unique, simple, and concise names.
* Dissociate test ID names from element text/labels.
* Do not utilize the element's text / label in the naming of a test ID!
### Finding Test IDs
* **MacOS Accessibility Inspector:** Use the built-in accessibility inspector to verify test IDs on iOS.
* **Detox Layout Inspector:** Set up and use the Detox Layout Inspector for Android.
* Incorrect or absent testID is a common cause for test failure. If your test can't find your testID and you can't see it either using tools described above, that usually means you haven't passed it down to this component.
Make sure you keep forwarding it down until it reaches a native component.
By following these best practices, you can create a robust and maintainable suite of Detox E2E tests for your React Native application.
@@ -0,0 +1,139 @@
---
description: This rule provides guidelines for writing clean, maintainable, and effective tests using Jest. It covers code organization, performance, common pitfalls, and best practices for testing JavaScript and TypeScript projects.
globs: **/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}
---
- **Organize tests by feature or module:**
- Group tests into files or directories that correspond to the features or modules they are testing. This makes it easier to locate and maintain tests.
- Create a `__tests__` directory alongside your source code files. This is a common convention that Jest recognizes.
- **Use descriptive test names:**
- Write test names that clearly describe what the test is verifying. This makes it easier to understand the purpose of each test and to diagnose failures.
- Use the `describe` and `it` blocks to structure your tests and provide context.
- Example: `describe('User authentication', () => { it('should log in a user with valid credentials', () => { /* ... */ }); });`
- **Keep tests isolated and independent:**
- Each test should be independent of other tests. Avoid sharing state or dependencies between tests.
- Use `beforeEach` and `afterEach` hooks to set up and tear down the environment for each test.
- **Avoid testing implementation details:**
- Focus on testing the public API of your code, rather than the internal implementation details.
- This makes your tests more resilient to changes in the implementation.
- Test the "what", not the "how".
- **Use setup and teardown methods:**
- Use `beforeAll`, `afterAll`, `beforeEach`, and `afterEach` hooks to set up and tear down the environment for your tests.
- `beforeAll` and `afterAll` run once before and after all tests in a `describe` block.
- `beforeEach` and `afterEach` run before and after each test in a `describe` block.
- **Mock external dependencies:**
- Use mocking to isolate your code from external dependencies, such as network requests or database connections.
- Jest provides built-in mocking capabilities with `jest.mock` and `jest.spyOn`.
- Consider using a library like `axios-mock-adapter` for mocking HTTP requests.
- **Write tests that are easy to read and maintain:**
- Keep your tests concise and focused.
- Use clear and consistent formatting.
- Add comments to explain complex logic.
- Refactor your tests regularly to keep them up to date.
- **Aim for high test coverage, but prioritize meaningful tests over quantity:**
- Aim for high test coverage to ensure that your code is well-tested.
- However, prioritize writing meaningful tests that verify the core functionality of your code.
- Don't just aim for 100% coverage without considering the value of each test.
- **Use Jest's built-in matchers effectively:**
- Jest provides a rich set of matchers for asserting different conditions.
- Use matchers like `toBe`, `toEqual`, `toBeGreaterThan`, `toContain`, `toHaveBeenCalled`, etc.
- Explore the Jest documentation for the full list of matchers.
- **Handle asynchronous code correctly:**
- Use `async/await` or Promises to handle asynchronous code in your tests.
- Use the `resolves` and `rejects` matchers to assert that a Promise resolves or rejects.
- Example: `expect(myAsyncFunction()).resolves.toBe(expectedValue);`
- **Test error handling:**
- Write tests to verify that your code handles errors correctly.
- Use the `toThrow` matcher to assert that a function throws an error.
- Example: `expect(() => myDangerousFunction()).toThrow(Error);`
- **Use snapshots sparingly:**
- Snapshots can be useful for verifying the output of a component or function.
- However, they can also be brittle and difficult to maintain if used excessively.
- Use snapshots strategically and review them carefully when they change.
- **Configure Jest correctly:**
- Configure Jest using the `jest.config.js` or `jest.config.ts` file.
- Configure settings such as test environment, module file extensions, and coverage thresholds.
- Consider using presets like `ts-jest` or `babel-jest` for TypeScript or Babel support.
- **Leverage code coverage reports:**
- Use Jest's code coverage reports to identify areas of your code that are not well-tested.
- Aim to increase coverage in critical areas of your codebase.
- Use the `--coverage` flag to generate coverage reports.
- **Keep test data separate from test logic:**
- Externalize test data to improve readability and maintainability.
- Use fixtures or factories to generate test data.
- Avoid hardcoding data directly in your tests.
- **Consider using test-driven development (TDD):**
- Write tests before you write code to drive the development process.
- This can help you write more testable and well-designed code.
- **Run tests frequently:**
- Run your tests frequently to catch errors early.
- Use Jest's watch mode to automatically run tests when files change.
- Integrate tests into your CI/CD pipeline.
- **Document your tests:**
- Add comments to explain the purpose of each test and the expected behavior.
- This will make it easier for others to understand and maintain your tests.
- **Code Organization and Structure:**
- **Directory structure best practices:** Organize test files alongside the component/module they test (e.g., `src/components/MyComponent/MyComponent.test.js`)
- **File naming conventions:** Use `.test.js` or `.spec.js` suffixes for test files (e.g., `MyComponent.test.js`, `MyModule.spec.ts`).
- **Module organization:** Keep test files close to the modules they are testing. Use a consistent naming convention for test files.
- **Component architecture:** Test components in isolation, mocking dependencies where necessary.
- **Code splitting strategies:** Ensure tests cover all code paths in dynamically imported modules.
- **Common Patterns and Anti-patterns:**
- **Design patterns specific to Jest:** Use Page Object Model (POM) for UI tests, Factory pattern for test data generation.
- **Recommended approaches for common tasks:** Use `jest.mock` for mocking modules, `jest.spyOn` for spying on methods, and `fakeTimers` for controlling time-dependent behavior.
- **Anti-patterns and code smells to avoid:** Avoid testing implementation details, relying on global state, and creating brittle snapshots.
- **State management best practices:** Mock external state dependencies and verify state changes using `expect` assertions.
- **Error handling patterns:** Test for specific error messages and ensure error boundaries are properly tested.
- **Performance Considerations:**
- **Optimization techniques:** Use `jest.clearAllMocks` and `jest.resetAllMocks` in `beforeEach` blocks to prevent state leakage and improve test performance.
- **Memory management:** Avoid creating large data structures in tests that are not necessary. Manually trigger garbage collection in tests where large objects are created and released.
- **Rendering optimization:** Mock expensive rendering logic to speed up tests that involve React components.
- **Bundle size optimization:** Not applicable, as Jest primarily tests individual modules or components.
- **Lazy loading strategies:** Ensure tests cover all code paths in dynamically imported modules.
- **Security Best Practices:**
- **Common vulnerabilities and how to prevent them:** Avoid using sensitive data in test snapshots. Sanitize test data to prevent potential injection attacks.
- **Input validation:** Test input validation logic and ensure that invalid inputs are handled correctly.
- **Authentication and authorization patterns:** Mock authentication and authorization logic to test different user roles and permissions.
- **Data protection strategies:** Not directly applicable, as Jest primarily focuses on functional testing.
- **Secure API communication:** Mock API calls and verify that data is transmitted securely.
- **Testing Approaches:**
- **Unit testing strategies:** Test individual functions, classes, or components in isolation.
- **Integration testing:** Test interactions between different modules or components.
- **End-to-end testing:** Use tools like Cypress or Playwright for end-to-end tests.
- **Test organization:** Group tests into logical suites based on functionality or module.
- **Mocking and stubbing:** Use `jest.mock` and `jest.spyOn` to create mocks and stubs for dependencies.
- **Common Pitfalls and Gotchas:**
- **Frequent mistakes developers make:** Forgetting to mock dependencies, testing implementation details, and creating brittle snapshots.
- **Edge cases to be aware of:** Testing asynchronous code correctly, handling errors, and testing different input types.
- **Version-specific issues:** Be aware of breaking changes in Jest updates and update your tests accordingly.
- **Compatibility concerns:** Ensure tests are compatible with different browsers or environments.
- **Debugging strategies:** Use `console.log` statements, debuggers, or Jest's interactive mode to debug tests.
- **Tooling and Environment:**
- **Recommended development tools:** VS Code, WebStorm, Jest Runner extension.
- **Build configuration:** Configure Jest using `jest.config.js` or `package.json`.
- **Linting and formatting:** Use ESLint and Prettier to enforce code style and prevent errors.
- **Deployment best practices:** Integrate tests into your CI/CD pipeline to ensure code quality.
- **CI/CD integration:** Use tools like GitHub Actions, Jenkins, or CircleCI to automate testing and deployment.
@@ -0,0 +1,151 @@
---
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
---
- **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.
- **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.
- **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) {}
async goto() {
await this.page.goto('/login');
}
async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#login-button');
}
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.
- **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.
- **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.
- **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.
- **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.
- **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.
- **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',
}
- **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.
@@ -0,0 +1,363 @@
---
description: This rule file provides comprehensive best practices for using Vitest, covering code organization, testing strategies, performance, and security within Vitest projects. These guidelines ensure clean, maintainable, and reliable test suites.
globs: **/*.{js,jsx,ts,tsx,vue,svelte,spec,test}.*
---
# Vitest Best Practices and Coding Standards
This document outlines best practices for using Vitest to create reliable, maintainable, and performant test suites. It covers various aspects of testing, from code organization to performance considerations and security measures.
## 1. Code Organization and Structure
### 1.1 Directory Structure
* **Keep tests close to the source code:** Place test files in the same directory as the components or modules they test. This improves discoverability and maintainability.
src/
components/
MyComponent.vue
MyComponent.spec.ts
MyComponent.test.ts # Alternative naming
utils/
math.ts
math.test.ts
App.vue
App.spec.ts
* **Use a dedicated `tests` directory for end-to-end tests or shared utilities:** For larger projects, a `tests` directory at the root level can house end-to-end tests, integration tests that require a specific environment, or shared testing utilities.
tests/
e2e/
specs/
home.spec.ts
support/
commands.ts
unit/
utils.test.ts # Tests for general utilities
integration/
db.setup.ts # Setup for integration tests
src/
...
### 1.2 File Naming Conventions
* **Use consistent naming:** Adopt a consistent naming scheme for test files. Common conventions include:
* `[component/module].spec.ts`
* `[component/module].test.ts`
* `[component/module].e2e.ts` (for end-to-end tests)
* **Be descriptive:** Name test files to clearly indicate what they are testing. For example, `MyComponent.props.spec.ts` might test specific props of `MyComponent`.
### 1.3 Module Organization
* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output.
typescript
import { describe, it, expect } from 'vitest';
import { add } from './math';
describe('Math functions', () => {
describe('add', () => {
it('should add two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
it('should handle negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});
});
});
### 1.4 Component Architecture
* **Test component logic separately:** Extract complex logic from components into separate, testable functions or modules. This promotes reusability and simplifies component testing.
* **Focus on component interactions:** When testing components, concentrate on verifying that the component renders correctly given certain props or state and that it emits the correct events in response to user interactions.
### 1.5 Code Splitting Strategies
* **Test code splitting:** If your application uses code splitting, ensure your tests cover different code chunks and lazy-loaded modules.
* **Mock dynamic imports:** Use Vitest's mocking capabilities to simulate dynamic imports during testing.
typescript
import { describe, it, expect, vi } from 'vitest';
describe('Dynamic import', () => {
it('should mock dynamic import', async () => {
const mockModule = { value: 'mocked' };
vi.mock('./dynamic-module', () => ({
default: mockModule,
}));
const dynamicModule = await import('./dynamic-module');
expect(dynamicModule.default).toBe(mockModule);
});
});
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to Vitest
* **AAA (Arrange, Act, Assert):** Structure each test case following the AAA pattern for clarity and maintainability.
typescript
it('should add two numbers correctly', () => {
// Arrange
const a = 2;
const b = 3;
// Act
const result = add(a, b);
// Assert
expect(result).toBe(5);
});
* **Page Object Model (POM):** For end-to-end tests, use the Page Object Model to abstract away the details of the user interface and make tests more resilient to UI changes. Define dedicated classes representing different pages or components.
### 2.2 Recommended Approaches for Common Tasks
* **Mocking external dependencies:** Use Vitest's mocking capabilities to isolate units of code during testing. Use `vi.mock()` to mock modules and `vi.spyOn()` to spy on specific methods or properties.
* **Testing asynchronous code:** Utilize `async/await` and Vitest's `expect.resolves` and `expect.rejects` matchers for testing asynchronous functions.
typescript
it('should resolve with the correct value', async () => {
await expect(Promise.resolve(42)).resolves.toBe(42);
});
it('should reject with an error', async () => {
await expect(Promise.reject(new Error('Something went wrong'))).rejects.toThrow('Something went wrong');
});
### 2.3 Anti-patterns and Code Smells to Avoid
* **Over-mocking:** Avoid mocking everything. Mock only external dependencies or components that are not under test. Testing against mocks rather than real implementations reduces test confidence.
* **Flaky tests:** Tests that pass or fail intermittently are a sign of underlying issues. Investigate flaky tests to identify and fix the root cause, such as race conditions or reliance on external resources.
* **Ignoring edge cases:** Ensure your tests cover all possible scenarios, including edge cases, error conditions, and boundary values. Don't only test the "happy path".
* **Long test functions:** Break down overly complex test functions into smaller, more focused tests. This improves readability and makes it easier to identify the cause of failures.
### 2.4 State Management Best Practices
* **Isolate state:** When testing code that relies on state management libraries (e.g., Vuex, Pinia, Redux), isolate the state and actions being tested.
* **Mock store actions/getters:** Mock actions and getters to control the state during testing and verify that they are called correctly.
typescript
import { describe, it, expect, vi } from 'vitest';
import { useStore } from './store';
describe('Store actions', () => {
it('should dispatch the correct action', () => {
const store = useStore();
const mockAction = vi.fn();
store.dispatch = mockAction;
store.commit('increment');
expect(mockAction).toHaveBeenCalledWith('increment');
});
});
### 2.5 Error Handling Patterns
* **Test error handling:** Ensure your tests cover error handling scenarios. Use `try...catch` blocks or `expect.rejects` to verify that errors are thrown and handled correctly.
* **Mock error responses:** Mock API responses to simulate error conditions and test how your code handles them.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Run tests in parallel:** Vitest supports running tests in parallel. Enable this feature to speed up test execution.
json
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
threads: true, // Enable parallel execution
},
})
* **Use `--changed` and `--related` flags:** When running tests, use the `--changed` flag to only run tests that have changed since the last commit or the `--related` flag to run tests related to specific files.
bash
vitest --changed
vitest --related src/components/MyComponent.vue
* **Optimize test setup:** Minimize the amount of setup required for each test. Use `beforeAll` and `afterAll` hooks to perform setup and teardown operations once for each test suite, rather than for each test case.
### 3.2 Memory Management
* **Clean up after tests:** Ensure that your tests do not leak memory. Use `afterEach` hooks to clean up any resources created during the test, such as mocks or temporary files.
* **Avoid creating large objects in tests:** Minimize the size of objects created in tests to reduce memory consumption.
### 3.3 Rendering Optimization
* **Use shallow rendering:** When testing components, use shallow rendering to avoid rendering the entire component tree. This can significantly improve test performance.
typescript
import { shallowMount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
it('should render correctly', () => {
const wrapper = shallowMount(MyComponent);
expect(wrapper.exists()).toBe(true);
});
### 3.4 Bundle Size Optimization
* **Keep tests small:** Avoid including unnecessary dependencies in your test files. This can help reduce the bundle size of your tests and improve startup time.
### 3.5 Lazy Loading Strategies
* **Mock lazy-loaded modules:** When testing code that uses lazy loading, mock the lazy-loaded modules to avoid loading them during testing. This can improve test performance and reduce dependencies.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and encoding output. Ensure the testing framework is not vulnerable either. Check versions of plugins.
* **Injection Attacks:** Prevent injection attacks by validating user input and using parameterized queries.
* **Sensitive Data Exposure:** Avoid storing sensitive data in test files. Use environment variables or secure configuration files to manage sensitive data.
### 4.2 Input Validation
* **Test input validation:** Ensure your tests cover input validation scenarios. Verify that your code correctly validates user input and handles invalid input gracefully.
### 4.3 Authentication and Authorization Patterns
* **Mock authentication:** When testing code that requires authentication, mock the authentication service to avoid making actual API calls. Verify that your code correctly handles authenticated and unauthenticated states.
* **Test authorization:** Ensure your tests cover authorization scenarios. Verify that your code correctly enforces access control and prevents unauthorized access to resources.
### 4.4 Data Protection Strategies
* **Protect sensitive data in tests:** Avoid including sensitive data in your test files. Use mock data or anonymized data for testing.
### 4.5 Secure API Communication
* **Mock API responses:** Mock API responses to avoid making actual API calls during testing. Use HTTPS for secure communication.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
* **Focus on individual units:** Unit tests should focus on testing individual functions, classes, or modules in isolation. Avoid testing multiple units of code in a single test.
* **Test all code paths:** Ensure your unit tests cover all possible code paths, including normal execution paths, error conditions, and edge cases.
* **Use mocks and stubs:** Use mocks and stubs to isolate units of code and control their behavior during testing.
### 5.2 Integration Testing
* **Test interactions between units:** Integration tests should focus on testing the interactions between different units of code. Verify that units of code work together correctly.
* **Use real dependencies:** Use real dependencies in integration tests whenever possible. This can help ensure that your code works correctly in a real-world environment.
### 5.3 End-to-End Testing
* **Test the entire application:** End-to-end tests should focus on testing the entire application, from the user interface to the backend services. Verify that the application works correctly from the user's perspective.
* **Use a real browser:** Use a real browser for end-to-end testing. This can help ensure that your application works correctly in different browsers and environments.
### 5.4 Test Organization
* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output. (See 1.3 Module Organization)
* **Use meaningful test names:** Use descriptive test names that clearly indicate what the test is verifying. This makes it easier to understand the purpose of the test and to identify the cause of failures.
* **Keep tests short and focused:** Keep tests short and focused on a single aspect of the code. This improves readability and makes it easier to maintain the tests.
### 5.5 Mocking and Stubbing
* **Use mocks to verify interactions:** Use mocks to verify that functions are called with the correct arguments and that they return the correct values.
* **Use stubs to control behavior:** Use stubs to control the behavior of functions during testing. This allows you to simulate different scenarios and test how your code handles them.
* **Avoid over-mocking:** Only mock dependencies that are not under test. Over-mocking can lead to tests that are brittle and do not accurately reflect the behavior of the code.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
* **Not writing enough tests:** Ensure that you have sufficient test coverage to catch bugs and prevent regressions.
* **Writing brittle tests:** Avoid writing tests that are too tightly coupled to the implementation details of the code. This makes the tests brittle and difficult to maintain.
* **Ignoring test failures:** Address test failures promptly. Ignoring test failures can lead to regressions and make it more difficult to maintain the code.
### 6.2 Edge Cases to Be Aware Of
* **Null and undefined values:** Ensure your tests cover scenarios where values are null or undefined.
* **Empty strings and arrays:** Ensure your tests cover scenarios where strings or arrays are empty.
* **Boundary values:** Ensure your tests cover boundary values, such as the minimum and maximum values of numeric types.
### 6.3 Version-Specific Issues
* **Keep Vitest up to date:** Stay up-to-date with the latest version of Vitest to benefit from bug fixes, performance improvements, and new features.
### 6.4 Compatibility Concerns
* **Test on different browsers and environments:** Ensure your tests cover different browsers and environments to catch compatibility issues.
### 6.5 Debugging Strategies
* **Use debugging tools:** Utilize debugging tools to step through your tests and identify the cause of failures. Vitest integrates with popular debuggers.
* **Write clear and concise tests:** Write clear and concise tests to make it easier to understand the purpose of the test and to identify the cause of failures.
* **Use logging:** Add logging statements to your tests to help track the flow of execution and identify the source of problems.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **VS Code with the Vitest extension:** VS Code with the Vitest extension provides a rich development experience, including test discovery, execution, and debugging.
* **Other IDEs with Vitest support:** Many other IDEs, such as WebStorm and IntelliJ IDEA, also offer support for Vitest.
### 7.2 Build Configuration
* **Use a build tool:** Use a build tool, such as Vite or esbuild, to bundle your code and optimize it for testing.
* **Configure Vitest:** Configure Vitest to suit your project's needs. Use the `vitest.config.ts` file to customize Vitest's behavior.
### 7.3 Linting and Formatting
* **Use ESLint and Prettier:** Use ESLint and Prettier to enforce consistent coding styles and catch potential errors. Integrate these tools into your development workflow.
### 7.4 Deployment Best Practices
* **Run tests before deployment:** Always run your tests before deploying your code to ensure that it is working correctly. Automate this process as part of your CI/CD pipeline.
### 7.5 CI/CD Integration
* **Integrate Vitest with your CI/CD pipeline:** Integrate Vitest with your CI/CD pipeline to automatically run tests on every commit. This helps catch bugs early and prevent regressions.
* **Use a CI/CD service:** Use a CI/CD service, such as GitHub Actions or GitLab CI, to automate your build, test, and deployment processes.
## Conclusion
By following these best practices, you can create robust and maintainable test suites with Vitest that ensure the quality and reliability of your code.