# Testing

Widgets built from the canonical template test with Vitest and Testing Library in a jsdom environment. Tests live in `tests/`, outside `src/`.

---

## Layout

`tests/` mirrors `src/`, plus two folders of its own:

```
tests/
├── app/                 # App.test.tsx, main.test.ts, mountTargets.test.ts
├── config/              # i18nConfig, liquidConfig, widgetConfig
├── features/
│   └── entities/        # one test per layer of the reference feature
│       ├── api/entityApi.test.ts
│       ├── hooks/useEntities.test.tsx
│       ├── model/entity.mapper.test.ts
│       └── ui/          # EntityListScreen, EntityCreateModal, entityCreateFlow
├── pages/
├── shared/
│   └── hooks/useDebouncedValue.test.tsx
├── boundaries/          # architecture, distContents, dynamicCssLink, styleBoundaries, widgetManifest
├── vite-plugins/        # lucideSubset
└── setup.ts
```

- **`tests/boundaries/`** checks the project as a whole: the import graph, the files in `dist/`, the Dynamic CSS link, the style boundaries and `widget.manifest.json`. Keep these tests; they fail when a change breaks one of those contracts.
- **A test for each hook at its mirrored path.** `src/<path>/useX.ts` is covered by `tests/<path>/useX.test.ts` (or `.tsx`, `.spec`). The validator checks this for `src/features/<name>/hooks` and `src/shared/hooks` (*Hooks Have Tests*, a warning: it does not affect `passing`).
- **No test files under `src/`** (validator *Test Folder Structure*, warning).
- A new feature copies `tests/features/entities` along with `src/features/entities`: see `modyo://docs/widgets/patterns-features`.

---

## Running

```bash
npm test            # vitest run
npm run test:watch  # vitest
```

`vite.config.ts` configures Vitest (`globals`, `environment: 'jsdom'`, `setupFiles: './tests/setup.ts'`). `tests/setup.ts` loads `@testing-library/jest-dom/vitest` and mocks `window.matchMedia` and `ResizeObserver`, which some Dynamic UI components need.

The template does not include a coverage provider. To measure coverage, install `@vitest/coverage-v8` with the same major version as `vitest` and run `npm run test -- --coverage`.

---

## Testing a feature's hooks

From `tests/features/entities/hooks/useEntities.test.tsx`: the `api/` module is mocked, and each test gets its own `QueryClient` with retries off.

```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import {
  entityKeys,
  useCreateEntity,
  useEntities,
} from '@/features/entities/hooks/useEntities';

const entityApi = vi.hoisted(() => ({
  getEntities: vi.fn(),
  createEntity: vi.fn(),
}));

vi.mock('@/features/entities/api/entityApi', () => entityApi);

const ENTITY = { id: '1', name: 'Uno', createdAt: '2024-01-01T00:00:00Z' };

function setup() {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  });
  const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
  return { queryClient, wrapper };
}

describe('useEntities', () => {
  beforeEach(() => {
    entityApi.getEntities.mockReset().mockResolvedValue([ENTITY]);
    entityApi.createEntity.mockReset();
  });

  it('pide la lista con los filtros y el signal de la query', async () => {
    const { wrapper } = setup();

    const { result } = renderHook(() => useEntities({ search: 'u' }), { wrapper });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.data).toEqual([ENTITY]);
    expect(entityApi.getEntities).toHaveBeenCalledWith({ search: 'u' }, expect.any(AbortSignal));
  });

  it('stores each filter combination under its own key', async () => {
    const { queryClient, wrapper } = setup();

    const { result } = renderHook(() => useEntities({ search: 'u' }), { wrapper });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(queryClient.getQueryData(entityKeys.list({ search: 'u' }))).toEqual([ENTITY]);
    expect(queryClient.getQueryData(entityKeys.list({}))).toBeUndefined();
  });

  it('expone el error de api/', async () => {
    entityApi.getEntities.mockRejectedValue(new Error('fallo'));
    const { wrapper } = setup();

    const { result } = renderHook(() => useEntities(), { wrapper });

    await waitFor(() => expect(result.current.isError).toBe(true));
  });
});

describe('useCreateEntity', () => {
  it('crea la entidad e invalida las listas', async () => {
    entityApi.getEntities.mockReset().mockResolvedValue([ENTITY]);
    entityApi.createEntity.mockReset().mockResolvedValue({ ...ENTITY, id: '2' });
    const { wrapper } = setup();

    const { result } = renderHook(
      () => ({ list: useEntities(), create: useCreateEntity() }),
      { wrapper },
    );
    await waitFor(() => expect(result.current.list.isSuccess).toBe(true));
    expect(entityApi.getEntities).toHaveBeenCalledTimes(1);

    await act(() => result.current.create.mutateAsync({ name: 'Dos' }));

    expect(entityApi.createEntity).toHaveBeenCalledWith({ name: 'Dos' });
    await waitFor(() => expect(entityApi.getEntities).toHaveBeenCalledTimes(2));
  });
});
```

What these tests assert is behavior: the data and the `AbortSignal` passed to `api/`, the error state, and the refetch after a mutation. A test that only renders and checks that nothing throws does not cover a hook.

Tests import from `@/…` paths, so they can reach a feature's internal layers directly.

---

## See also

- `modyo://docs/widgets/patterns-features` — feature layers and their tests
- `modyo://docs/widgets/patterns-tanstack-query` — the hooks under test
- `modyo://docs/widgets/reference-validator-rules` — *Testing* rules
