Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Convert integration test to unit test

fzaninotto1da390a8a18e
diff --git a/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.integration.test.tsx b/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.integration.test.tsx
deleted file mode 100644
index c01208ee..00000000
--- a/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.integration.test.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { render } from "vitest-browser-react";
-import { ListContextProvider } from "ra-core";
-import {
- createCrmDb,
- createCrmScenario,
- CrmTestProvider,
-} from "@/test/browser/atomic-crm/crmUiHarness";
-import { NotesIteratorMobile } from "./NotesIteratorMobile";
-
-const singleNote = {
- contact_id: 3,
- date: "2026-03-17T13:50:00.000Z",
- id: 9,
- sales_id: 0,
- status: "warm",
- text: "Only note in the list",
-};
-
-// Trigger the infinite-pagination sentinel immediately in tests so we can
-// assert whether mounting the list would request another page.
-class ImmediateIntersectionObserver implements IntersectionObserver {
- readonly root = null;
- readonly rootMargin = "0px";
- readonly thresholds = [0];
-
- constructor(private readonly callback: IntersectionObserverCallback) {}
-
- disconnect() {}
-
- observe(target: Element) {
- this.callback(
- [
- {
- boundingClientRect: target.getBoundingClientRect(),
- intersectionRatio: 1,
- intersectionRect: target.getBoundingClientRect(),
- isIntersecting: true,
- rootBounds: null,
- target,
- time: Date.now(),
- },
- ],
- this,
- );
- }
-
- takeRecords() {
- return [];
- }
-
- unobserve() {}
-}
-
-const NotesIteratorHarness = ({
- setPage,
-}: {
- setPage: ReturnType<typeof vi.fn>;
-}) => {
- const listContext = {
- data: [singleNote],
- defaultTitle: undefined,
- displayedFilters: {},
- error: null,
- exporter: false,
- filterValues: {},
- hasNextPage: false,
- hasPreviousPage: false,
- hideFilter: vi.fn(),
- isFetching: false,
- isLoading: false,
- isPaused: false,
- isPending: false,
- onSelect: vi.fn(),
- onSelectAll: vi.fn(),
- onToggleItem: vi.fn(),
- onUnselectItems: vi.fn(),
- page: 1,
- perPage: 25,
- refetch: vi.fn(),
- resource: "contact_notes",
- selectedIds: [],
- setFilters: vi.fn(),
- setPage,
- setPerPage: vi.fn(),
- setSort: vi.fn(),
- showFilter: vi.fn(),
- sort: { field: "date", order: "DESC" },
- total: 1,
- } as any;
-
- return (
- <ListContextProvider value={listContext}>
- <NotesIteratorMobile contactId={3} showStatus />
- </ListContextProvider>
- );
-};
-
-describe("NotesIteratorMobile pagination integration", () => {
- it("does not request the next page on mount when the first page already contains the full result set", async () => {
- const originalIntersectionObserver = window.IntersectionObserver;
- window.IntersectionObserver =
- ImmediateIntersectionObserver as unknown as typeof IntersectionObserver;
-
- try {
- const setPage = vi.fn();
- const scenario = createCrmScenario({
- db: createCrmDb(),
- latency: 0,
- });
-
- const screen = await render(
- <CrmTestProvider scenario={scenario}>
- <NotesIteratorHarness setPage={setPage} />
- </CrmTestProvider>,
- );
-
- await expect
- .element(screen.getByText("Only note in the list"))
- .toBeInTheDocument();
- expect(setPage).not.toHaveBeenCalled();
- } finally {
- window.IntersectionObserver = originalIntersectionObserver;
- }
- });
-});
diff --git a/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.stories.tsx b/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.stories.tsx
new file mode 100644
index 00000000..52321755
--- /dev/null
+++ b/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.stories.tsx
@@ -0,0 +1,76 @@
+import type { Meta } from "@storybook/react-vite";
+import type { ReactNode } from "react";
+import { ListContextProvider } from "ra-core";
+
+import { NotesIteratorMobile } from "./NotesIteratorMobile";
+import { StoryWrapper } from "@/test/browser/atomic-crm/crmUiHarness";
+
+const singleNote = {
+ contact_id: 3,
+ date: "2026-03-17T13:50:00.000Z",
+ id: 9,
+ sales_id: 0,
+ status: "warm",
+ text: "Only note in the list",
+};
+
+const meta = {
+ title: "Atomic CRM/Notes/NotesIteratorMobile Pagination",
+ parameters: {
+ layout: "fullscreen",
+ },
+ globals: {
+ viewport: { value: "mobile1", isRotated: false },
+ },
+} satisfies Meta;
+
+export default meta;
+
+export const SingleNote = ({
+ children,
+ setPage = () => {},
+}: {
+ children?: ReactNode;
+ setPage?: (...args: unknown[]) => void;
+}) => {
+ const listContext = {
+ data: [singleNote],
+ defaultTitle: undefined,
+ displayedFilters: {},
+ error: null,
+ exporter: false,
+ filterValues: {},
+ hasNextPage: false,
+ hasPreviousPage: false,
+ hideFilter: () => {},
+ isFetching: false,
+ isLoading: false,
+ isPaused: false,
+ isPending: false,
+ onSelect: () => {},
+ onSelectAll: () => {},
+ onToggleItem: () => {},
+ onUnselectItems: () => {},
+ page: 1,
+ perPage: 25,
+ refetch: () => {},
+ resource: "contact_notes",
+ selectedIds: [],
+ setFilters: () => {},
+ setPage,
+ setPerPage: () => {},
+ setSort: () => {},
+ showFilter: () => {},
+ sort: { field: "date", order: "DESC" },
+ total: 1,
+ } as any;
+
+ return (
+ <StoryWrapper data={{ contact_notes: [singleNote] }}>
+ <ListContextProvider value={listContext}>
+ <NotesIteratorMobile contactId={3} showStatus />
+ </ListContextProvider>
+ {children}
+ </StoryWrapper>
+ );
+};
diff --git a/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.test.tsx b/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.test.tsx
new file mode 100644
index 00000000..240b096f
--- /dev/null
+++ b/src/components/atomic-crm/notes/NotesIteratorMobile.pagination.test.tsx
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from "vitest";
+import { render } from "vitest-browser-react";
+import { SingleNote } from "./NotesIteratorMobile.pagination.stories";
+
+// Trigger the infinite-pagination sentinel immediately in tests so we can
+// assert whether mounting the list would request another page.
+class ImmediateIntersectionObserver implements IntersectionObserver {
+ readonly root = null;
+ readonly rootMargin = "0px";
+ readonly thresholds = [0];
+
+ constructor(private readonly callback: IntersectionObserverCallback) {}
+
+ disconnect() {}
+
+ observe(target: Element) {
+ this.callback(
+ [
+ {
+ boundingClientRect: target.getBoundingClientRect(),
+ intersectionRatio: 1,
+ intersectionRect: target.getBoundingClientRect(),
+ isIntersecting: true,
+ rootBounds: null,
+ target,
+ time: Date.now(),
+ },
+ ],
+ this,
+ );
+ }
+
+ takeRecords() {
+ return [];
+ }
+
+ unobserve() {}
+}
+
+describe("NotesIteratorMobile pagination", () => {
+ it("does not request the next page on mount when the first page already contains the full result set", async () => {
+ const originalIntersectionObserver = window.IntersectionObserver;
+ window.IntersectionObserver =
+ ImmediateIntersectionObserver as unknown as typeof IntersectionObserver;
+
+ try {
+ const setPage = vi.fn();
+
+ const screen = await render(<SingleNote setPage={setPage} />);
+
+ await expect
+ .element(screen.getByText("Only note in the list"))
+ .toBeInTheDocument();
+ expect(setPage).not.toHaveBeenCalled();
+ } finally {
+ window.IntersectionObserver = originalIntersectionObserver;
+ }
+ });
+});
diff --git a/src/components/atomic-crm/notes/useAddInfinitePagination.integration.test.tsx b/src/components/atomic-crm/notes/useAddInfinitePagination.test.tsx
similarity index 100%
rename from src/components/atomic-crm/notes/useAddInfinitePagination.integration.test.tsx
rename to src/components/atomic-crm/notes/useAddInfinitePagination.test.tsx
diff --git a/src/test/browser/atomic-crm/crmUiHarness.tsx b/src/test/browser/atomic-crm/crmUiHarness.tsx
index 06afa99f..ae4a3599 100644
--- a/src/test/browser/atomic-crm/crmUiHarness.tsx
+++ b/src/test/browser/atomic-crm/crmUiHarness.tsx
@@ -1,97 +1,15 @@
/* eslint-disable react-refresh/only-export-components */
+import { memoryStore, type AuthProvider } from "ra-core";
+import { useMemo, type ReactNode } from "react";
+import { MemoryRouter } from "react-router";
import { Notification } from "@/components/admin/notification";
-import { ThemeProvider } from "@/components/admin/theme-provider";
-import { ContactList } from "@/components/atomic-crm/contacts/ContactList";
-import { ContactShow } from "@/components/atomic-crm/contacts/ContactShow";
-import {
- ContactListContent,
- ContactListContentMobile,
-} from "@/components/atomic-crm/contacts/ContactListContent";
import { createDataProvider } from "@/components/atomic-crm/providers/fakerest";
import { DEFAULT_USER } from "@/components/atomic-crm/providers/fakerest/authProvider";
import type { Db } from "@/components/atomic-crm/providers/fakerest/dataGenerator/types";
-import { CONFIGURATION_STORE_KEY } from "@/components/atomic-crm/root/ConfigurationContext";
-import { defaultConfiguration } from "@/components/atomic-crm/root/defaultConfiguration";
-import { i18nProvider } from "@/components/atomic-crm/providers/commons/i18nProvider";
-import type {
- Company,
- Contact,
- Sale,
- Tag,
- Task,
-} from "@/components/atomic-crm/types";
-import {
- CoreAdminContext,
- ResourceContextProvider,
- ResourceDefinitionContextProvider,
- localStorageStore,
- memoryStore,
- type AuthProvider,
-} from "ra-core";
-import { useMemo, type ReactNode } from "react";
-import { MemoryRouter } from "react-router";
+import type { Contact, Sale } from "@/components/atomic-crm/types";
import { CRM } from "@/components/atomic-crm/root/CRM";
import { testI18nProvider } from "@/components/atomic-crm/providers/commons/i18nProvider";
-let scenarioCount = 0;
-
-const wait = async (ms: number) =>
- new Promise((resolve) => {
- window.setTimeout(resolve, ms);
- });
-
-const getContactName = (record?: Contact) =>
- `${record?.first_name ?? ""} ${record?.last_name ?? ""}`.trim();
-
-const getCompanyName = (record?: Company) => record?.name ?? "";
-const getSaleName = (record?: Sale) =>
- `${record?.first_name ?? ""} ${record?.last_name ?? ""}`.trim();
-const getTagName = (record?: Tag) => record?.name ?? "";
-const getTaskName = (record?: Task) => record?.text ?? "";
-
-const resourceDefinitions = {
- companies: {
- hasList: true,
- name: "companies",
- recordRepresentation: getCompanyName,
- },
- configuration: {
- name: "configuration",
- },
- contact_notes: {
- hasList: true,
- name: "contact_notes",
- },
- contacts: {
- hasCreate: true,
- hasList: true,
- hasShow: true,
- name: "contacts",
- recordRepresentation: getContactName,
- },
- contacts_summary: {
- hasList: true,
- name: "contacts_summary",
- recordRepresentation: getContactName,
- },
- sales: {
- hasList: true,
- name: "sales",
- recordRepresentation: getSaleName,
- },
- tags: {
- hasList: true,
- name: "tags",
- recordRepresentation: getTagName,
- },
- tasks: {
- hasCreate: true,
- hasList: true,
- name: "tasks",
- recordRepresentation: getTaskName,
- },
-};
-
export const createTestAuthProvider = (): AuthProvider => ({
canAccess: async () => true,
checkAuth: async () => undefined,
@@ -117,20 +35,6 @@ const baseSale: Sale = {
user_id: DEFAULT_USER.id.toString(),
};
-export interface CrmScenarioOptions {
- db?: Db;
- failGetListOnce?: Partial<Record<string, string>>;
- getListDelays?: Partial<Record<string, number>>;
- latency?: number;
-}
-
-export interface CrmScenario {
- authProvider: AuthProvider;
- dataProvider: ReturnType<typeof createDataProvider>;
- db: Db;
- store: ReturnType<typeof localStorageStore>;
-}
-
// Provide a minimal FakeRest database shape so tests can override only the records
// that matter for each scenario.
export const createCrmDb = (overrides: Partial<Db> = {}): Db =>
@@ -170,124 +74,6 @@ export const buildContact = (overrides: Partial<Contact> = {}): Contact => ({
...overrides,
});
-// Create an isolated CRM runtime backed by FakeRest, with optional delays and
-// one-shot failures to exercise loading and error states.
-export const createCrmScenario = ({
- db = createCrmDb(),
- failGetListOnce = {},
- getListDelays = {},
- latency = 0,
-}: CrmScenarioOptions = {}): CrmScenario => {
- const authProvider = createTestAuthProvider();
- const baseDataProvider = createDataProvider({
- authProvider,
- db,
- latency,
- });
- const pendingFailures = new Map(Object.entries(failGetListOnce));
- const dataProvider = {
- ...baseDataProvider,
- getList: async (resource, params) => {
- const delayMs = getListDelays[resource] ?? 0;
- if (delayMs > 0) {
- await wait(delayMs);
- }
-
- const failureMessage = pendingFailures.get(resource);
- if (failureMessage) {
- pendingFailures.delete(resource);
- throw new Error(failureMessage);
- }
-
- return baseDataProvider.getList(resource, params);
- },
- } as ReturnType<typeof createDataProvider>;
- const store = localStorageStore(
- undefined,
- `CRM_TEST_${(scenarioCount += 1)}`,
- );
- store.setItem(CONFIGURATION_STORE_KEY, defaultConfiguration);
-
- return {
- authProvider,
- dataProvider,
- db,
- store,
- };
-};
-
-// Mount the minimum react-admin and app providers required by the CRM widgets
-// under test, without booting the full application shell.
-export const CrmTestProvider = ({
- children,
- className,
- initialEntries = ["/"],
- resource,
- scenario,
-}: {
- children: ReactNode;
- className?: string;
- initialEntries?: string[];
- resource?: string;
- scenario: CrmScenario;
-}) => (
- <MemoryRouter initialEntries={initialEntries}>
- <CoreAdminContext
- authProvider={scenario.authProvider}
- dataProvider={scenario.dataProvider}
- i18nProvider={i18nProvider}
- store={scenario.store}
- >
- <ResourceDefinitionContextProvider definitions={resourceDefinitions}>
- <ThemeProvider>
- <div className={className}>
- {resource ? (
- <ResourceContextProvider value={resource}>
- {children}
- </ResourceContextProvider>
- ) : (
- children
- )}
- </div>
- <Notification />
- </ThemeProvider>
- </ResourceDefinitionContextProvider>
- </CoreAdminContext>
- </MemoryRouter>
-);
-
-// Reuse the same scenario factory in Storybook so stories match the integration
-// test environment as closely as possible.
-export const CrmStoryProvider = ({
- children,
- className,
- initialEntries,
- resource,
- scenarioOptions,
-}: {
- children: ReactNode;
- className?: string;
- initialEntries?: string[];
- resource?: string;
- scenarioOptions: CrmScenarioOptions;
-}) => {
- const scenario = useMemo(
- () => createCrmScenario(scenarioOptions),
- [scenarioOptions],
- );
-
- return (
- <CrmTestProvider
- className={className}
- initialEntries={initialEntries}
- resource={resource}
- scenario={scenario}
- >
- {children}
- </CrmTestProvider>
- );
-};
-
export const StoryWrapper = ({
children,
data,