mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +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:
+405
-164
@@ -1,178 +1,419 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for using Apollo Client in your projects, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in building robust and maintainable GraphQL-powered applications.
|
||||
globs: *.js,*.jsx,*.ts,*.tsx,*.gql,*.graphql
|
||||
description: This guide defines the definitive best practices for using Apollo Client 3.x in our React applications, focusing on cache hygiene, type safety, performance, and maintainability.
|
||||
globs: **/*.{js,jsx}
|
||||
---
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Organize GraphQL queries and mutations in a dedicated directory (e.g., `graphql` or `queries`).
|
||||
- Group related queries and mutations into subdirectories based on features or modules.
|
||||
- Consider a separate directory for GraphQL types/schemas if you're managing them locally.
|
||||
- Example:
|
||||
|
||||
src/
|
||||
graphql/
|
||||
user/
|
||||
getUser.gql
|
||||
createUser.gql
|
||||
product/
|
||||
getProduct.gql
|
||||
updateProduct.gql
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for GraphQL query and mutation files (e.g., `getUser.gql`, `updateProduct.gql`).
|
||||
- Employ a consistent naming scheme (e.g., `[operationName].[operationType].gql`).
|
||||
- **Module Organization:**
|
||||
- Encapsulate Apollo Client logic (e.g., initialization, hooks) within reusable modules.
|
||||
- Create custom hooks for common data fetching patterns (e.g., `useUser`, `useProduct`).
|
||||
- **Component Architecture:**
|
||||
- Favor a component-based architecture for UI development.
|
||||
- Decouple data fetching logic from UI components using hooks or render props.
|
||||
- Utilize higher-order components (HOCs) or render props for cross-cutting concerns (e.g., authentication, error handling).
|
||||
- **Code Splitting:**
|
||||
- Use dynamic imports to lazy-load components and queries, improving initial load time.
|
||||
- Split large queries into smaller fragments to reduce bundle size.
|
||||
# apollo-client Best Practices
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Facade Pattern:** Provide a simplified interface to a complex subsystem (e.g., Apollo Client).
|
||||
- **Hook Composition:** Combine multiple custom hooks to create more complex data fetching logic.
|
||||
- **Recommended Approaches:**
|
||||
- Use the `useQuery` and `useMutation` hooks for data fetching and manipulation.
|
||||
- Leverage Apollo Client's cache for improved performance and offline capabilities.
|
||||
- Implement optimistic updates to provide a better user experience.
|
||||
- Use GraphQL fragments to reuse common data structures across multiple queries and mutations.
|
||||
- **Anti-patterns:**
|
||||
- Avoid directly manipulating the Apollo Client cache outside of mutations.
|
||||
- Don't fetch the entire schema unnecessarily; only fetch what you need.
|
||||
- Avoid deeply nested components with complex data fetching logic.
|
||||
- **State Management:**
|
||||
- Use Apollo Client's cache as the primary source of truth for application state.
|
||||
- Integrate with external state management libraries (e.g., Redux, Zustand) when necessary for complex state requirements.
|
||||
- Consider using Apollo Link State for managing local client-side state.
|
||||
- **Error Handling:**
|
||||
- Implement global error handling with Apollo Link.
|
||||
- Display user-friendly error messages to the user.
|
||||
- Retry failed queries or mutations automatically.
|
||||
Apollo Client is our standard for GraphQL state management. Adhering to these guidelines ensures predictable data flow, optimal performance, and a scalable codebase.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use the `fetchPolicy` option in `useQuery` to control cache behavior.
|
||||
- Implement pagination for large datasets.
|
||||
- Use batching and caching at the server-side to reduce network requests.
|
||||
- **Memory Management:**
|
||||
- Unsubscribe from subscriptions when components unmount to prevent memory leaks.
|
||||
- Avoid storing large amounts of data in the Apollo Client cache.
|
||||
- **Rendering Optimization:**
|
||||
- Use React's `memo` or `useMemo` to prevent unnecessary re-renders.
|
||||
- Implement virtualization for rendering large lists.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused dependencies.
|
||||
- Minify and compress your code.
|
||||
- **Lazy Loading:**
|
||||
- Lazy-load components and queries using dynamic imports.
|
||||
---
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **GraphQL Injection:** Prevent injection attacks by validating user input and using parameterized queries.
|
||||
- **Denial of Service (DoS):** Limit query complexity and depth to prevent DoS attacks.
|
||||
- **Information Disclosure:** Avoid exposing sensitive data in error messages.
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client and server sides.
|
||||
- Use GraphQL's built-in validation capabilities.
|
||||
- **Authentication and Authorization:**
|
||||
- Implement proper authentication and authorization mechanisms.
|
||||
- Use JWT (JSON Web Tokens) or other secure authentication protocols.
|
||||
- Follow the principle of least privilege when granting access to data.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS for all API communication.
|
||||
- **Secure API Communication:**
|
||||
- Use Apollo Link to add security headers to API requests.
|
||||
- Implement CORS (Cross-Origin Resource Sharing) to prevent cross-site scripting (XSS) attacks.
|
||||
## 1. Client Setup & Initialization
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Test individual components and hooks in isolation.
|
||||
- Mock Apollo Client's API to control data fetching behavior.
|
||||
- **Integration Testing:**
|
||||
- Test the integration of components with Apollo Client.
|
||||
- Use a test GraphQL server to simulate real API interactions.
|
||||
- **End-to-end Testing:**
|
||||
- Test the entire application flow from the user interface to the backend.
|
||||
- Use tools like Cypress or Puppeteer for end-to-end testing.
|
||||
- **Test Organization:**
|
||||
- Organize tests in a directory structure that mirrors the source code.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., Jest, Sinon) to mock Apollo Client's API.
|
||||
- Create stub GraphQL responses for testing different scenarios.
|
||||
**Always instantiate `ApolloClient` as a singleton.** Avoid creating multiple client instances, as each client manages its own `InMemoryCache`, leading to inconsistent state and wasted resources.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- Incorrect cache configuration leading to stale data.
|
||||
- Over-fetching data in GraphQL queries.
|
||||
- Ignoring error handling in `useQuery` and `useMutation`.
|
||||
- **Edge Cases:**
|
||||
- Handling network errors and offline scenarios.
|
||||
- Dealing with large datasets and complex queries.
|
||||
- Managing cache invalidation and updates.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Apollo Client versions.
|
||||
- Consult the Apollo Client documentation for migration guides.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different browsers and devices.
|
||||
- Test your application on different platforms.
|
||||
- **Debugging Strategies:**
|
||||
- Use Apollo Client DevTools to inspect queries, mutations, and cache state.
|
||||
- Log API requests and responses for debugging purposes.
|
||||
❌ **BAD:** Multiple `ApolloClient` instances
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Tools:**
|
||||
- Apollo Client DevTools for debugging and inspecting the cache.
|
||||
- GraphQL Playground or GraphiQL for exploring and testing GraphQL APIs.
|
||||
- Apollo VS Code extension for syntax highlighting and autocompletion.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Webpack or Parcel to bundle your code.
|
||||
- Configure Babel to transpile your code to compatible JavaScript versions.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce code style and best practices.
|
||||
- Configure linting rules specific to Apollo Client and GraphQL.
|
||||
- **Deployment:**
|
||||
- Use a deployment platform like Netlify, Vercel, or AWS Amplify.
|
||||
- Configure environment variables for API endpoints and other sensitive data.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD pipeline to automate testing and deployment.
|
||||
- Integrate linters, formatters, and test runners into the pipeline.
|
||||
```javascript
|
||||
// In multiple files
|
||||
const client = new ApolloClient({ /* ... */ });
|
||||
```
|
||||
|
||||
- **Specific Best Practices based on Exa Search Results:**
|
||||
- Ensure all queries for a specific type return an ID for normalization and caching (RedwoodJS Community).
|
||||
- Store queries in separate `.gql` files and use tools like `graphql-import` for better organization (Reddit).
|
||||
- Use Apollo Client's `watchQuery` method for real-time data updates (Medium).
|
||||
- Follow GraphQL query best practices for efficient API design (Apollo GraphQL).
|
||||
✅ **GOOD:** Singleton `ApolloClient`
|
||||
|
||||
- **Additional considerations**
|
||||
- When creating queries and mutations, follow best practices to get the most out of both GraphQL and Apollo tooling.
|
||||
```javascript
|
||||
// src/apolloClient.js
|
||||
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
|
||||
import { onError } from '@apollo/client/link/error';
|
||||
import { RetryLink } from '@apollo/client/link/retry';
|
||||
|
||||
- **Example Directory Structure**
|
||||
const httpLink = new HttpLink({
|
||||
uri: process.env.GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql',
|
||||
headers: {
|
||||
authorization: localStorage.getItem('token') || '',
|
||||
'client-name': 'OurApp [web]',
|
||||
'client-version': '1.0.0',
|
||||
},
|
||||
});
|
||||
|
||||
src/
|
||||
components/
|
||||
UserCard.tsx
|
||||
ProductDetails.tsx
|
||||
graphql/
|
||||
queries/
|
||||
getUser.gql
|
||||
getProduct.gql
|
||||
mutations/
|
||||
createUser.gql
|
||||
updateProduct.gql
|
||||
hooks/
|
||||
useUser.ts
|
||||
useProduct.ts
|
||||
utils/
|
||||
apolloClient.ts // Initialize Apollo Client here
|
||||
const errorLink = onError(({ graphQLErrors, networkError }) => {
|
||||
if (graphQLErrors)
|
||||
graphQLErrors.forEach(({ message, locations, path }) =>
|
||||
console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
|
||||
);
|
||||
if (networkError) console.error(`[Network error]: ${networkError}`);
|
||||
});
|
||||
|
||||
const retryLink = new RetryLink({
|
||||
delay: {
|
||||
initial: 300,
|
||||
max: Infinity,
|
||||
jitter: true
|
||||
},
|
||||
attempts: {
|
||||
max: 5,
|
||||
retryIf: (error, _operation) => !!error
|
||||
}
|
||||
});
|
||||
|
||||
This is a comprehensive guide for using Apollo Client. Please adapt these guidelines to your specific project requirements and coding style.
|
||||
export const client = new ApolloClient({
|
||||
link: from([errorLink, retryLink, httpLink]),
|
||||
cache: new InMemoryCache({
|
||||
typePolicies: {
|
||||
// Define type policies here for custom cache behavior
|
||||
User: {
|
||||
keyFields: ['id'], // Ensure consistent identification
|
||||
},
|
||||
Query: {
|
||||
fields: {
|
||||
// Example: Custom merge for a paginated list
|
||||
users: {
|
||||
keyArgs: false, // Don't include arguments in cache key
|
||||
merge(existing = [], incoming) {
|
||||
return [...existing, ...incoming];
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
// Enable Automatic Persisted Queries for performance
|
||||
persistedQueries: {
|
||||
ttl: 3600, // 1 hour
|
||||
},
|
||||
});
|
||||
|
||||
// src/App.js
|
||||
import { ApolloProvider } from '@apollo/client';
|
||||
import { client } from './apolloClient';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ApolloProvider client={client}>
|
||||
{/* Your application */}
|
||||
</ApolloProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Data Fetching with React Hooks
|
||||
|
||||
**Always use Apollo Client's React hooks (`useQuery`, `useMutation`, `useSubscription`) for data operations within components.** These hooks provide declarative data fetching, automatic UI updates, and robust state management. Avoid direct `client.query()` or `client.mutate()` calls in components unless for specific server-side rendering or pre-fetching scenarios outside the React lifecycle.
|
||||
|
||||
❌ **BAD:** Imperative data fetching in components
|
||||
|
||||
```javascript
|
||||
import { client } from '../apolloClient';
|
||||
|
||||
function MyComponent() {
|
||||
const [data, setData] = useState(null);
|
||||
useEffect(() => {
|
||||
client.query({ query: GET_USERS }).then(res => setData(res.data));
|
||||
}, []);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD:** Declarative data fetching with `useQuery`
|
||||
|
||||
```javascript
|
||||
import { useQuery, gql } from '@apollo/client';
|
||||
|
||||
const GET_USERS = gql`
|
||||
query GetUsers($limit: Int!) {
|
||||
users(limit: $limit) {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
function UserList({ limit }) {
|
||||
const { loading, error, data } = useQuery(GET_USERS, {
|
||||
variables: { limit },
|
||||
fetchPolicy: 'cache-and-network', // Recommended for most lists
|
||||
});
|
||||
|
||||
if (loading) return <p>Loading users...</p>;
|
||||
if (error) return <p>Error: {error.message}</p>;
|
||||
|
||||
return (
|
||||
<ul>
|
||||
{data.users.map(user => (
|
||||
<li key={user.id}>{user.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Cache Hygiene & Management
|
||||
|
||||
**Prioritize immutable cache updates and configure `InMemoryCache` with `TypePolicy` and `FieldPolicy`.** This prevents stale data, ensures garbage collection, and customizes merging logic for complex data structures.
|
||||
|
||||
**`fetchPolicy` Strategy:**
|
||||
* `cache-first` (default): Use for stable data that rarely changes.
|
||||
* `cache-and-network`: Use for data that might change frequently, providing instant UI feedback while fetching fresh data.
|
||||
* `network-only`: Use for critical, real-time data or mutations where the latest server state is paramount.
|
||||
* `no-cache`: Use for one-off data (e.g., authentication tokens) that should *never* be stored in the cache.
|
||||
|
||||
❌ **BAD:** Mutating cache objects directly or neglecting `keyFields`
|
||||
|
||||
```javascript
|
||||
// This can lead to inconsistent cache state
|
||||
cache.data.data.User:123.name = 'New Name';
|
||||
```
|
||||
|
||||
✅ **GOOD:** Immutable cache updates with `cache.modify` or `writeFragment`
|
||||
|
||||
```javascript
|
||||
import { useMutation, gql } from '@apollo/client';
|
||||
|
||||
const UPDATE_USER_NAME = gql`
|
||||
mutation UpdateUserName($id: ID!, $name: String!) {
|
||||
updateUserName(id: $id, name: $name) {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
function UserProfile({ userId, currentName }) {
|
||||
const [updateName] = useMutation(UPDATE_USER_NAME);
|
||||
|
||||
const handleUpdate = async (newName) => {
|
||||
await updateName({
|
||||
variables: { id: userId, name: newName },
|
||||
update: (cache, { data: { updateUserName } }) => {
|
||||
cache.modify({
|
||||
id: cache.identify(updateUserName), // Get normalized cache ID
|
||||
fields: {
|
||||
name() {
|
||||
return updateUserName.name; // Update the name field
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Current Name: {currentName}</p>
|
||||
<button onClick={() => handleUpdate('Jane Doe')}>Change Name</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Type Safety & Code Generation
|
||||
|
||||
**Mandate `@graphql-codegen` for all GraphQL operations.** This generates TypeScript types for queries, mutations, and subscriptions, along with typed React hooks, ensuring end-to-end type safety and reducing runtime errors.
|
||||
|
||||
❌ **BAD:** Manual type definitions or `any`
|
||||
|
||||
```javascript
|
||||
// Manually defining types is error-prone and tedious
|
||||
interface UserData {
|
||||
users: Array<{ id: string; name: string }>;
|
||||
}
|
||||
const { data } = useQuery<UserData>(GET_USERS);
|
||||
```
|
||||
|
||||
✅ **GOOD:** Generated types and hooks
|
||||
|
||||
```javascript
|
||||
// graphql.config.js (example)
|
||||
module.exports = {
|
||||
schema: 'http://localhost:4000/graphql',
|
||||
documents: 'src/**/*.graphql',
|
||||
overwrite: true,
|
||||
generates: {
|
||||
'./src/generated/graphql.tsx': {
|
||||
plugins: [
|
||||
'typescript',
|
||||
'typescript-operations',
|
||||
'typescript-react-apollo',
|
||||
],
|
||||
config: {
|
||||
withHooks: true,
|
||||
withHOC: false,
|
||||
withComponent: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// src/components/UserList.graphql (separate file for GraphQL document)
|
||||
// query GetUsers($limit: Int!) {
|
||||
// users(limit: $limit) {
|
||||
// id
|
||||
// name
|
||||
// }
|
||||
// }
|
||||
|
||||
// src/components/UserList.tsx
|
||||
import { useGetUsersQuery } from '../generated/graphql'; // Generated hook
|
||||
|
||||
function UserList({ limit }) {
|
||||
const { loading, error, data } = useGetUsersQuery({ variables: { limit } });
|
||||
|
||||
if (loading) return <p>Loading users...</p>;
|
||||
if (error) return <p>Error: {error.message}</p>;
|
||||
|
||||
return (
|
||||
<ul>
|
||||
{data?.users.map(user => ( // Data is now fully typed
|
||||
<li key={user.id}>{user.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Error Handling & Resilience
|
||||
|
||||
**Implement centralized error handling using Apollo Link's `onError` and `RetryLink`.** This provides a consistent way to log, display, and recover from network and GraphQL errors.
|
||||
|
||||
❌ **BAD:** Inconsistent error handling across components
|
||||
|
||||
```javascript
|
||||
// Every component handles errors differently
|
||||
if (error) {
|
||||
alert(error.message);
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD:** Centralized error handling with `onError` link (see Section 1 for example) and component-level display.
|
||||
|
||||
```javascript
|
||||
// In a component using useQuery or useMutation
|
||||
function MyComponent() {
|
||||
const { loading, error, data } = useQuery(MY_QUERY);
|
||||
|
||||
if (loading) return <p>Loading...</p>;
|
||||
if (error) {
|
||||
// Specific UI for this component's error
|
||||
return <p className="error-message">Failed to load data: {error.message}</p>;
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Code Organization & Naming Conventions
|
||||
|
||||
**Colocate GraphQL documents (`.graphql` files) with the components that use them.** Follow GraphQL schema naming conventions (`camelCase` for fields/arguments, `PascalCase` for types, `SCREAMING_SNAKE_CASE` for enum values) and enforce them with GraphOS schema linting.
|
||||
|
||||
❌ **BAD:** Inline GraphQL strings, generic naming
|
||||
|
||||
```javascript
|
||||
// In a large component file
|
||||
const MY_HUGE_QUERY = gql`query { /* ... */ }`;
|
||||
```
|
||||
|
||||
✅ **GOOD:** Dedicated GraphQL files, clear naming
|
||||
|
||||
```
|
||||
// src/components/UserList/
|
||||
// ├── UserList.tsx
|
||||
// └── UserList.graphql
|
||||
```
|
||||
|
||||
```graphql
|
||||
# src/components/UserList/UserList.graphql
|
||||
query GetUsers($limit: Int!) {
|
||||
users(limit: $limit) {
|
||||
id
|
||||
firstName # Use camelCase for fields
|
||||
lastName
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 7. Performance Considerations
|
||||
|
||||
**Utilize fragments for query reuse and to avoid over-fetching.** Consider Automatic Persisted Queries (APQ) for production environments to reduce network payload sizes. Optimize `fetchPolicy` based on data volatility.
|
||||
|
||||
❌ **BAD:** Repeated field selections, large monolithic queries
|
||||
|
||||
```graphql
|
||||
query GetUserAndPosts {
|
||||
user(id: "1") { id name email }
|
||||
posts(userId: "1") { id title content }
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD:** Use fragments for modularity and reuse
|
||||
|
||||
```graphql
|
||||
# src/fragments/UserFragment.graphql
|
||||
fragment UserDetails on User {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
|
||||
# src/components/UserPosts/UserPosts.graphql
|
||||
query GetUserAndPosts($userId: ID!) {
|
||||
user(id: $userId) {
|
||||
...UserDetails
|
||||
}
|
||||
posts(userId: $userId) {
|
||||
id
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 8. Testing Approaches
|
||||
|
||||
**Use `@apollo/client/testing`'s `MockedProvider` for unit and integration tests of components that use Apollo hooks.** This allows you to mock GraphQL operations and control the data returned, ensuring consistent and isolated tests.
|
||||
|
||||
❌ **BAD:** Relying on a live GraphQL API for component tests
|
||||
|
||||
```javascript
|
||||
// This makes tests slow, flaky, and dependent on external services
|
||||
render(<MyComponent />);
|
||||
```
|
||||
|
||||
✅ **GOOD:** Mocking GraphQL responses with `MockedProvider`
|
||||
|
||||
```javascript
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { MockedProvider } from '@apollo/client/testing';
|
||||
import { GET_USERS } from './UserList.graphql'; // Import your GraphQL document
|
||||
import UserList from './UserList';
|
||||
|
||||
const mocks = [
|
||||
{
|
||||
request: {
|
||||
query: GET_USERS,
|
||||
variables: { limit: 10 },
|
||||
},
|
||||
result: {
|
||||
data: {
|
||||
users: [
|
||||
{ id: '1', name: 'Alice' },
|
||||
{ id: '2', name: 'Bob' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
test('renders user list', async () => {
|
||||
render(
|
||||
<MockedProvider mocks={mocks} addTypename={false}>
|
||||
<UserList limit={10} />
|
||||
</MockedProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/loading users.../i)).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bob')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user