AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
dx(frontend): set up React integration testing with Vitest + RTL + MSW (#12667)
Ubbea11199aa67d9
diff --git a/.claude/skills/write-frontend-tests/SKILL.md b/.claude/skills/write-frontend-tests/SKILL.mdnew file mode 100644index 0000000000..177ce64a68--- /dev/null+++ b/.claude/skills/write-frontend-tests/SKILL.md@@ -0,0 +1,224 @@+---+name: write-frontend-tests+description: "Analyze the current branch diff against dev, plan integration tests for changed frontend pages/components, and write them. TRIGGER when user asks to write frontend tests, add test coverage, or 'write tests for my changes'."+user-invocable: true+args: "[base branch] — defaults to dev. Optionally pass a specific base branch to diff against."+metadata:+ author: autogpt-team+ version: "1.0.0"+---++# Write Frontend Tests++Analyze the current branch's frontend changes, plan integration tests, and write them.++## References++Before writing any tests, read the testing rules and conventions:++- `autogpt_platform/frontend/TESTING.md` — testing strategy, file locations, examples+- `autogpt_platform/frontend/src/tests/AGENTS.md` — detailed testing rules, MSW patterns, decision flowchart+- `autogpt_platform/frontend/src/tests/integrations/test-utils.tsx` — custom render with providers+- `autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx` — MSW server setup++## Step 1: Identify changed frontend files++```bash+BASE_BRANCH="${ARGUMENTS:-dev}"+cd autogpt_platform/frontend++# Get changed frontend files (excluding generated, config, and test files)+git diff "$BASE_BRANCH"...HEAD --name-only -- src/ \+ | grep -v '__generated__' \+ | grep -v '__tests__' \+ | grep -v '\.test\.' \+ | grep -v '\.stories\.' \+ | grep -v '\.spec\.'+```++Also read the diff to understand what changed:++```bash+git diff "$BASE_BRANCH"...HEAD --stat -- src/+git diff "$BASE_BRANCH"...HEAD -- src/ | head -500+```++## Step 2: Categorize changes and find test targets++For each changed file, determine:++1. **Is it a page?** (`page.tsx`) — these are the primary test targets+2. **Is it a hook?** (`use*.ts`) — test via the page that uses it+3. **Is it a component?** (`.tsx` in `components/`) — test via the parent page unless it's complex enough to warrant isolation+4. **Is it a helper?** (`helpers.ts`, `utils.ts`) — unit test directly if pure logic++**Priority order:**+1. Pages with new/changed data fetching or user interactions+2. Components with complex internal logic (modals, forms, wizards)+3. Hooks with non-trivial business logic+4. Pure helper functions++Skip: styling-only changes, type-only changes, config changes.++## Step 3: Check for existing tests++For each test target, check if tests already exist:++```bash+# For a page at src/app/(platform)/library/page.tsx+ls src/app/\(platform\)/library/__tests__/ 2>/dev/null++# For a component at src/app/(platform)/library/components/AgentCard/AgentCard.tsx+ls src/app/\(platform\)/library/components/AgentCard/__tests__/ 2>/dev/null+```++Note which targets have no tests (need new files) vs which have tests that need updating.++## Step 4: Identify API endpoints used++For each test target, find which API hooks are used:++```bash+# Find generated API hook imports in the changed files+grep -rn 'from.*__generated__/endpoints' src/app/\(platform\)/library/+grep -rn 'use[A-Z].*V[12]' src/app/\(platform\)/library/+```++For each API hook found, locate the corresponding MSW handler:++```bash+# If the page uses useGetV2ListLibraryAgents, find its MSW handlers+grep -rn 'getGetV2ListLibraryAgents.*Handler' src/app/api/__generated__/endpoints/library/library.msw.ts+```++List every MSW handler you will need (200 for happy path, 4xx for error paths).++## Step 5: Write the test plan++Before writing code, output a plan as a numbered list:++```+Test plan for [branch name]:++1. src/app/(platform)/library/__tests__/main.test.tsx (NEW)+ - Renders page with agent list (MSW 200)+ - Shows loading state+ - Shows error state (MSW 422)+ - Handles empty agent list++2. src/app/(platform)/library/__tests__/search.test.tsx (NEW)+ - Filters agents by search query+ - Shows no results message+ - Clears search++3. src/app/(platform)/library/components/AgentCard/__tests__/AgentCard.test.tsx (UPDATE)+ - Add test for new "duplicate" action+```++Present this plan to the user. Wait for confirmation before proceeding. If the user has feedback, adjust the plan.++## Step 6: Write the tests++For each test file in the plan, follow these conventions:++### File structure++```tsx+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+// Import MSW handlers for endpoints the page uses+import {+ getGetV2ListLibraryAgentsMockHandler200,+ getGetV2ListLibraryAgentsMockHandler422,+} from "@/app/api/__generated__/endpoints/library/library.msw";+// Import the component under test+import LibraryPage from "../page";++describe("LibraryPage", () => {+ test("renders agent list from API", async () => {+ server.use(getGetV2ListLibraryAgentsMockHandler200());++ render(<LibraryPage />);++ expect(await screen.findByText(/my agents/i)).toBeDefined();+ });++ test("shows error state on API failure", async () => {+ server.use(getGetV2ListLibraryAgentsMockHandler422());++ render(<LibraryPage />);++ expect(await screen.findByText(/error/i)).toBeDefined();+ });+});+```++### Rules++- Use `render()` from `@/tests/integrations/test-utils` (NOT from `@testing-library/react` directly)+- Use `server.use()` to set up MSW handlers BEFORE rendering+- Use `findBy*` (async) for elements that appear after data fetching — NOT `getBy*`+- Use `getBy*` only for elements that are immediately present in the DOM+- Use `screen` queries — do NOT destructure from `render()`+- Use `waitFor` when asserting side effects or state changes after interactions+- Import `fireEvent` or `userEvent` from the test-utils for interactions+- Do NOT mock internal hooks or functions — mock at the API boundary via MSW+- Do NOT use `act()` manually — `render` and `fireEvent` handle it+- Keep tests focused: one behavior per test+- Use descriptive test names that read like sentences++### Test location++```+# For pages: __tests__/ next to page.tsx+src/app/(platform)/library/__tests__/main.test.tsx++# For complex standalone components: __tests__/ inside component folder+src/app/(platform)/library/components/AgentCard/__tests__/AgentCard.test.tsx++# For pure helpers: co-located .test.ts+src/app/(platform)/library/helpers.test.ts+```++### Custom MSW overrides++When the auto-generated faker data is not enough, override with specific data:++```tsx+import { http, HttpResponse } from "msw";++server.use(+ http.get("http://localhost:3000/api/proxy/api/v2/library/agents", () => {+ return HttpResponse.json({+ agents: [+ { id: "1", name: "Test Agent", description: "A test agent" },+ ],+ pagination: { total_items: 1, total_pages: 1, page: 1, page_size: 10 },+ });+ }),+);+```++Use the proxy URL pattern: `http://localhost:3000/api/proxy/api/v{version}/{path}` — this matches the MSW base URL configured in `orval.config.ts`.++## Step 7: Run and verify++After writing all tests:++```bash+cd autogpt_platform/frontend+pnpm test:unit --reporter=verbose+```++If tests fail:+1. Read the error output carefully+2. Fix the test (not the source code, unless there is a genuine bug)+3. Re-run until all pass++Then run the full checks:++```bash+pnpm format+pnpm lint+pnpm types+```diff --git a/AGENTS.md b/AGENTS.mdindex f88741ae3a..d0b325167c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,7 +30,7 @@ See `/frontend/CONTRIBUTING.md` for complete patterns. Quick reference:- Regenerate with `pnpm generate:api`- Pattern: `use{Method}{Version}{OperationName}`4. **Styling**: Tailwind CSS only, use design tokens, Phosphor Icons only-5. **Testing**: Add Storybook stories for new components, Playwright for E2E+5. **Testing**: Integration tests (Vitest + RTL + MSW) are the default (~90%, page-level). Playwright for E2E critical flows. Storybook for design system components. See `autogpt_platform/frontend/TESTING.md`6. **Code conventions**: Function declarations (not arrow functions) for components/handlers- Component props should be `interface Props { ... }` (not exported) unless the interface needs to be used outside the component@@ -47,7 +47,9 @@ See `/frontend/CONTRIBUTING.md` for complete patterns. Quick reference:## Testing- Backend: `poetry run test` (runs pytest with a docker based postgres + prisma).-- Frontend: `pnpm test` or `pnpm test-ui` for Playwright tests. See `docs/content/platform/contributing/tests.md` for tips.+- Frontend integration tests: `pnpm test:unit` (Vitest + RTL + MSW, primary testing approach).+- Frontend E2E tests: `pnpm test` or `pnpm test-ui` for Playwright tests.+- See `autogpt_platform/frontend/TESTING.md` for the full testing strategy.Always run the relevant linters and tests before committing.Use conventional commit messages for all commits (e.g. `feat(backend): add API`).diff --git a/autogpt_platform/frontend/AGENTS.md b/autogpt_platform/frontend/AGENTS.mdindex e0accaadc1..152d0f239d 100644--- a/autogpt_platform/frontend/AGENTS.md+++ b/autogpt_platform/frontend/AGENTS.md@@ -40,6 +40,8 @@ After making **any** code changes in the frontend, you MUST run the following coDo NOT skip these steps. If any command reports errors, fix them and re-run until clean. Only then may you consider the task complete. If typing keeps failing, stop and ask the user.+4. `pnpm test:unit` — run integration tests; fix any failures+### Code Style- Fully capitalize acronyms in symbols, e.g. `graphID`, `useBackendAPI`@@ -62,7 +64,7 @@ Do NOT skip these steps. If any command reports errors, fix them and re-run unti- **Icons**: Phosphor Icons only- **Feature Flags**: LaunchDarkly integration- **Error Handling**: ErrorCard for render errors, toast for mutations, Sentry for exceptions-- **Testing**: Playwright for E2E, Storybook for component development+- **Testing**: Vitest + React Testing Library + MSW for integration tests (primary), Playwright for E2E, Storybook for visual## Environment Configuration@@ -84,7 +86,12 @@ See @CONTRIBUTING.md for complete patterns. Quick reference:- Regenerate with `pnpm generate:api`- Pattern: `use{Method}{Version}{OperationName}`4. **Styling**: Tailwind CSS only, use design tokens, Phosphor Icons only-5. **Testing**: Add Storybook stories for new components, Playwright for E2E. When fixing a bug, write a failing Playwright test first (use `.fixme` annotation), implement the fix, then remove the annotation.+5. **Testing**: Integration tests are the default (~90%). See `TESTING.md` for full details.+ - **New pages/features**: Write integration tests in `__tests__/` next to `page.tsx` using Vitest + RTL + MSW+ - **API mocking**: Use Orval-generated MSW handlers from `@/app/api/__generated__/endpoints/{tag}/{tag}.msw.ts`+ - **Run**: `pnpm test:unit` (integration/unit), `pnpm test` (Playwright E2E)+ - **Storybook**: For design system components in `src/components/`+ - **TDD**: Write a failing test first, implement, then verify6. **Code conventions**:- Use function declarations (not arrow functions) for components/handlers- Do not use `useCallback` or `useMemo` unless asked to optimise a given functiondiff --git a/autogpt_platform/frontend/CONTRIBUTING.md b/autogpt_platform/frontend/CONTRIBUTING.mdindex 649bb1ca92..bcb40f4430 100644--- a/autogpt_platform/frontend/CONTRIBUTING.md+++ b/autogpt_platform/frontend/CONTRIBUTING.md@@ -747,9 +747,65 @@ export function CreateButton() {----## 🧪 Testing & Storybook+## 🧪 Testing-- See `TESTING.md` for Playwright setup, E2E data seeding, and Storybook usage.+See `TESTING.md` for full details. Key principles:++### Integration tests are the default (~90% of tests)++We test at the **page level**: render the page with React Testing Library, mock API requests with MSW (auto-generated by Orval), and assert with testing-library queries.++```bash+pnpm test:unit # run integration/unit tests+pnpm test:unit:watch # watch mode+```++### Test file location++Tests live in `__tests__/` next to the page or component:++```+app/(platform)/library/+ __tests__/+ main.test.tsx # main page rendering & interactions+ search.test.tsx # search-specific behavior+ components/+ page.tsx+ useLibraryPage.ts+```++### Writing a test++1. Render the page using `render()` from `@/tests/integrations/test-utils`+2. Mock API responses using Orval-generated MSW handlers from `@/app/api/__generated__/endpoints/{tag}/{tag}.msw.ts`+3. Assert with `screen.findByText`, `screen.getByRole`, etc.++```tsx+import { render, screen } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import { getGetV2ListLibraryAgentsMockHandler200 } from "@/app/api/__generated__/endpoints/library/library.msw";+import LibraryPage from "../page";++test("renders agent list", async () => {+ server.use(getGetV2ListLibraryAgentsMockHandler200());+ render(<LibraryPage />);+ expect(await screen.findByText("My Agents")).toBeDefined();+});+```++### When to use each test type++| Type | When |+| ------------------------------------ | --------------------------------------------- |+| **Integration (Vitest + RTL + MSW)** | Default for all new pages and features |+| **E2E (Playwright)** | Auth flows, payments, cross-page navigation |+| **Storybook** | Design system components in `src/components/` |++### TDD workflow++1. Write a failing test (integration test or Playwright with `.fixme`)+2. Implement the fix/feature+3. Remove annotations and run the full suite---@@ -763,8 +819,10 @@ Common scripts (see `package.json` for full list):- `pnpm lint` — ESLint + Prettier check- `pnpm format` — Format code- `pnpm types` — Type-check+- `pnpm test:unit` — Run integration/unit tests (Vitest + RTL + MSW)+- `pnpm test:unit:watch` — Watch mode for integration tests+- `pnpm test` — Run Playwright E2E tests- `pnpm storybook` — Run Storybook-- `pnpm test` — Run Playwright testsGenerated API client:@@ -780,6 +838,7 @@ Generated API client:- Logic is separated into `use*.ts` and `helpers.ts` when non-trivial- Reusable logic extracted to `src/services/` or `src/lib/utils.ts` when appropriate- Navigation uses the Next.js router+- Integration tests added/updated for new pages and features (`pnpm test:unit`)- Lint, format, type-check, and tests pass locally- Stories updated/added if UI changed; verified in Storybookdiff --git a/autogpt_platform/frontend/TESTING.md b/autogpt_platform/frontend/TESTING.mdindex 2995295c96..0b95f8eaab 100644--- a/autogpt_platform/frontend/TESTING.md+++ b/autogpt_platform/frontend/TESTING.md@@ -1,57 +1,168 @@-# Frontend Testing 🧪+# Frontend Testing-## Quick Start (local) 🚀+## Testing Strategy++| Type | Tool | Speed | When to use |+| ------------------------- | ------------------------------------ | ------------- | ----------------------------------------------------- |+| **Integration (primary)** | Vitest + React Testing Library + MSW | Fast (~100ms) | ~90% of tests — page-level rendering with mocked API |+| **E2E** | Playwright | Slow (~5s) | Critical flows: auth, payments, cross-page navigation |+| **Visual** | Storybook + Chromatic | N/A | Design system components |++**Integration tests are the default.** Since most of our code is client-only, we test at the page level: render the page with React Testing Library, mock API requests with MSW (handlers auto-generated by Orval), and assert with testing-library queries.++## Integration Tests (Vitest + RTL + MSW)++### Running++```bash+pnpm test:unit # run all integration/unit tests with coverage+pnpm test:unit:watch # watch mode for development+```++### File location++Tests live in a `__tests__/` folder next to the page or component they test:++```+app/(platform)/library/+ __tests__/+ main.test.tsx # tests the main page rendering & interactions+ search.test.tsx # tests search-specific behavior+ components/+ AgentCard/+ AgentCard.tsx+ __tests__/+ AgentCard.test.tsx # only when testing the component in isolation+ page.tsx+ useLibraryPage.ts+```++**Naming**: use descriptive names like `main.test.tsx`, `search.test.tsx`, `filters.test.tsx` — not `page.test.tsx` or `index.test.tsx`.++### Writing an integration test++1. **Render the page** using the custom `render()` from `@/tests/integrations/test-utils` (wraps providers)+2. **Mock API responses** using Orval-generated MSW handlers from `@/app/api/__generated__/endpoints/{tag}/{tag}.msw.ts`+3. **Assert** with React Testing Library queries (`screen.findByText`, `screen.getByRole`, etc.)++```tsx+import { render, screen } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import {+ getGetV2ListLibraryAgentsMockHandler200,+ getGetV2ListLibraryAgentsMockHandler422,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import LibraryPage from "../page";++describe("LibraryPage", () => {+ test("renders agent list from API", async () => {+ server.use(getGetV2ListLibraryAgentsMockHandler200());++ render(<LibraryPage />);++ expect(await screen.findByText("My Agents")).toBeDefined();+ });++ test("shows error state on API failure", async () => {+ server.use(getGetV2ListLibraryAgentsMockHandler422());++ render(<LibraryPage />);++ expect(await screen.findByText(/error/i)).toBeDefined();+ });+});+```++### MSW handlers++Orval generates typed MSW handlers for every endpoint and HTTP status code:++- `getGetV2ListLibraryAgentsMockHandler200()` — success response with faker data+- `getGetV2ListLibraryAgentsMockHandler422()` — validation error response+- `getGetV2ListLibraryAgentsMockHandler401()` — unauthorized response++To override with custom data, pass a resolver:++```tsx+import { http, HttpResponse } from "msw";++server.use(+ http.get("http://localhost:3000/api/proxy/api/library/agents", () => {+ return HttpResponse.json({+ agents: [{ id: "1", name: "My Agent" }],+ pagination: { total: 1 },+ });+ }),+);+```++All handlers are aggregated in `src/mocks/mock-handlers.ts` and the MSW server is set up in `src/mocks/mock-server.ts`.++### Test utilities++- **`@/tests/integrations/test-utils`** — custom `render()` that wraps components with `QueryClientProvider`, `BackendAPIProvider`, `OnboardingProvider`, `NuqsTestingAdapter`, and `TooltipProvider`, so query-state hooks and tooltips work out of the box in page-level tests+- **`@/tests/integrations/setup-nextjs-mocks`** — mocks for `next/navigation`, `next/image`, `next/headers`, `next/link`+- **`@/tests/integrations/mock-supabase-request`** — mocks Supabase auth (returns null user by default)++### What to test at page level++- Page renders with API data (happy path)+- Loading and error states+- User interactions that trigger mutations (clicks, form submissions)+- Conditional rendering based on API responses+- Search, filtering, pagination behavior++### When to test a component in isolation++Only when the component has complex internal logic that is hard to exercise through the page test. Prefer page-level tests as the default.++## E2E Tests (Playwright)++### Running++```bash+pnpm test # build + run all Playwright tests+pnpm test-ui # run with Playwright UI+pnpm test:no-build # run against a running dev server+```++### Setup1. Start the backend + Supabase stack:- From `autogpt_platform`: `docker compose --profile local up deps_backend -d`- - Or run the full stack: `docker compose up -d`2. Seed rich E2E data (creates `[email protected]` with library agents):- From `autogpt_platform/backend`: `poetry run python test/e2e_test_data.py`-3. Run Playwright:- - From `autogpt_platform/frontend`: `pnpm test` or `pnpm test-ui`--## How Playwright setup works 🎭--- Playwright runs from `frontend/playwright.config.ts` with a global setup step.-- The global setup creates a user pool via the real signup UI and stores it in `frontend/.auth/user-pool.json`.-- Most tests call `getTestUser()` (from `src/tests/utils/auth.ts`) which pulls a random user from that pool.- - these users do not contain library agents, it's user that just "signed up" on the platform, hence some tests to make use of users created via script (see below) with more data-## Test users 👤+### How Playwright setup works-- **User pool (basic users)**- Created automatically by the Playwright global setup through `/signup`.- Used by `getTestUser()` in `src/tests/utils/auth.ts`.+- Playwright runs from `frontend/playwright.config.ts` with a global setup step+- Global setup creates a user pool via the real signup UI, stored in `frontend/.auth/user-pool.json`+- `getTestUser()` (from `src/tests/utils/auth.ts`) pulls a random user from the pool+- `getTestUserWithLibraryAgents()` uses the rich user created by the data script-- **Rich user with library agents**- Created by `backend/test/e2e_test_data.py`.- Accessed via `getTestUserWithLibraryAgents()` in `src/tests/credentials/index.ts`.+### Test users-Use the rich user when a test needs existing library agents (e.g. `library.spec.ts`).+- **User pool (basic users)** — created automatically by Playwright global setup. Used by `getTestUser()`+- **Rich user with library agents** — created by `backend/test/e2e_test_data.py`. Used by `getTestUserWithLibraryAgents()`-## Resetting or wiping the DB 🔁+### Resetting the DBIf you reset the Docker DB and logins start failing:-1. Delete `frontend/.auth/user-pool.json` so the pool is regenerated.-2. Re-run the E2E data script to recreate the rich user + library agents:- - `poetry run python test/e2e_test_data.py`+1. Delete `frontend/.auth/user-pool.json`+2. Re-run `poetry run python test/e2e_test_data.py`-## Storybook 📚+## Storybook-## Flow diagram 🗺️+- `pnpm storybook` — run locally+- `pnpm build-storybook` — build static+- `pnpm test-storybook` — CI runner+- When changing components in `src/components`, update or add stories and verify in Storybook/Chromatic-```mermaid-flowchart TD- A[Start Docker stack] --> B[Run e2e_test_data.py]- B --> C[Run Playwright tests]- C --> D[Global setup creates user pool]- D --> E{Test needs rich data?}- E -->|No| F[getTestUser from user pool]- E -->|Yes| G[getTestUserWithLibraryAgents]-```+## TDD Workflow++When fixing a bug or adding a feature:-- `pnpm storybook` – Run Storybook locally-- `pnpm build-storybook` – Build a static Storybook-- CI runner: `pnpm test-storybook`-- When changing components in `src/components`, update or add stories and verify in Storybook/Chromatic.+1. **Write a failing test first** — for integration tests, write the test and confirm it fails. For Playwright, use `.fixme` annotation+2. **Implement the fix/feature** — write the minimal code to make the test pass+3. **Remove annotations** — once passing, remove `.fixme` and run the full suitediff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsxnew file mode 100644index 0000000000..8d7960dc9b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx@@ -0,0 +1,223 @@+import { describe, expect, test } from "vitest";+import { render, screen } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import {+ getGetV2ListLibraryAgentsMockHandler,+ getGetV2ListLibraryAgentsResponseMock,+ getGetV2ListFavoriteLibraryAgentsMockHandler,+ getGetV2ListFavoriteLibraryAgentsResponseMock,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import {+ getGetV2ListLibraryFoldersMockHandler,+ getGetV2ListLibraryFoldersResponseMock,+} from "@/app/api/__generated__/endpoints/folders/folders.msw";+import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import LibraryPage from "../page";++function makeAgent(overrides: Partial<LibraryAgent> = {}): LibraryAgent {+ const base = getGetV2ListLibraryAgentsResponseMock().agents[0];+ return { ...base, ...overrides };+}++function setupHandlers({+ agents,+ favorites,+ folders,+ executions,+}: {+ agents?: LibraryAgent[];+ favorites?: LibraryAgent[];+ folders?: Parameters<typeof getGetV2ListLibraryFoldersResponseMock>[0];+ executions?: Parameters<typeof getGetV1ListAllExecutionsMockHandler>[0];+} = {}) {+ const agentList = agents ?? [makeAgent()];+ const favList = favorites ?? [];++ server.use(+ getGetV2ListLibraryAgentsMockHandler({+ ...getGetV2ListLibraryAgentsResponseMock(),+ agents: agentList,+ pagination: {+ total_items: agentList.length,+ total_pages: 1,+ current_page: 1,+ page_size: 20,+ },+ }),+ getGetV2ListFavoriteLibraryAgentsMockHandler({+ ...getGetV2ListFavoriteLibraryAgentsResponseMock(),+ agents: favList,+ pagination: {+ total_items: favList.length,+ total_pages: 1,+ current_page: 1,+ page_size: 10,+ },+ }),+ getGetV2ListLibraryFoldersMockHandler(+ folders+ ? getGetV2ListLibraryFoldersResponseMock(folders)+ : {+ folders: [],+ pagination: {+ total_items: 0,+ total_pages: 1,+ current_page: 1,+ page_size: 20,+ },+ },+ ),+ getGetV1ListAllExecutionsMockHandler(executions ?? []),+ );+}++function waitForAgentsToLoad() {+ return screen.findAllByTestId("library-agent-card-name");+}++describe("LibraryPage", () => {+ test("renders agent cards from API", async () => {+ setupHandlers({ agents: [makeAgent({ name: "Weather Bot" })] });++ render(<LibraryPage />);++ expect(await screen.findByText("Weather Bot")).toBeDefined();+ });++ test("renders multiple agent cards with correct names", async () => {+ setupHandlers({+ agents: [+ makeAgent({ id: "a1", name: "Agent Alpha" }),+ makeAgent({ id: "a2", name: "Agent Beta" }),+ makeAgent({ id: "a3", name: "Agent Gamma" }),+ ],+ });++ render(<LibraryPage />);++ expect(await screen.findByText("Agent Alpha")).toBeDefined();+ expect(screen.getByText("Agent Beta")).toBeDefined();+ expect(screen.getByText("Agent Gamma")).toBeDefined();+ });++ test("renders All and Favorites tabs", async () => {+ setupHandlers();++ render(<LibraryPage />);++ await waitForAgentsToLoad();++ const tabs = screen.getAllByRole("tab");+ const tabNames = tabs.map((t) => t.textContent);+ expect(tabNames.some((n) => n?.match(/all/i))).toBe(true);+ expect(tabNames.some((n) => n?.match(/favorites/i))).toBe(true);+ });++ test("favorites tab is disabled when no favorites exist", async () => {+ setupHandlers();++ render(<LibraryPage />);++ await waitForAgentsToLoad();++ const favoritesTab = screen+ .getAllByRole("tab")+ .find((t) => t.textContent?.match(/favorites/i));+ expect(favoritesTab).toBeDefined();+ expect(favoritesTab!.hasAttribute("data-disabled")).toBe(true);+ });++ test("renders folders alongside agents", async () => {+ setupHandlers({+ folders: {+ folders: [+ {+ id: "f1",+ user_id: "test-user",+ name: "Work Agents",+ agent_count: 3,+ color: null,+ icon: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ {+ id: "f2",+ user_id: "test-user",+ name: "Personal",+ agent_count: 1,+ color: null,+ icon: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ ],+ },+ });++ render(<LibraryPage />);++ expect(await screen.findByText("Work Agents")).toBeDefined();+ expect(screen.getByText("Personal")).toBeDefined();+ expect(screen.getAllByTestId("library-folder")).toHaveLength(2);+ });++ test("shows See runs link on agent card", async () => {+ setupHandlers({+ agents: [makeAgent({ name: "Linked Agent", can_access_graph: true })],+ });++ render(<LibraryPage />);++ await screen.findByText("Linked Agent");++ const runLinks = screen.getAllByText("See runs");+ expect(runLinks.length).toBeGreaterThan(0);+ });++ test("renders search bar and import button", async () => {+ setupHandlers();++ render(<LibraryPage />);++ await waitForAgentsToLoad();++ const searchBars = screen.getAllByTestId("library-textbox");+ expect(searchBars.length).toBeGreaterThan(0);++ const importButtons = screen.getAllByTestId("import-button");+ expect(importButtons.length).toBeGreaterThan(0);+ });++ test("renders Jump Back In when there is an active execution", async () => {+ const agent = makeAgent({+ id: "lib-1",+ graph_id: "g-1",+ name: "Running Agent",+ });+ setupHandlers({+ agents: [agent],+ executions: [+ {+ id: "exec-1",+ user_id: "test-user",+ graph_id: "g-1",+ graph_version: 1,+ inputs: {},+ credential_inputs: {},+ nodes_input_masks: {},+ preset_id: null,+ status: "RUNNING",+ started_at: new Date(Date.now() - 60_000),+ ended_at: null,+ stats: null,+ },+ ],+ });++ render(<LibraryPage />);++ expect(await screen.findByText("Jump Back In")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx b/autogpt_platform/frontend/src/tests/integrations/test-utils.tsxindex dbe424a88b..c708f1c4e6 100644--- a/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx+++ b/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx@@ -1,7 +1,9 @@+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";import OnboardingProvider from "@/providers/onboarding/onboarding-provider";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, RenderOptions } from "@testing-library/react";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";import { ReactElement, ReactNode } from "react";function createTestQueryClient() {@@ -18,9 +20,13 @@ function TestProviders({ children }: { children: ReactNode }) {const queryClient = createTestQueryClient();return (<QueryClientProvider client={queryClient}>- <BackendAPIProvider>- <OnboardingProvider>{children}</OnboardingProvider>- </BackendAPIProvider>+ <NuqsTestingAdapter>+ <BackendAPIProvider>+ <OnboardingProvider>+ <TooltipProvider>{children}</TooltipProvider>+ </OnboardingProvider>+ </BackendAPIProvider>+ </NuqsTestingAdapter></QueryClientProvider>);}