import { screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import heroContent from '@/content/heroContent';
import { renderWithProviders } from '@/test/renderWithProviders';
import type { LoadJson } from '@/components/PackagesProvider/PackagesProvider';
import useHero from './useHero';
const answer = (title: string) => ({
title,
slides: [
{
id: 'a',
alt: 'Alt',
decorative: false,
image: { width: 10, height: 8, src: '/m/a.webp' },
},
],
});
function Title({ load }: { load: LoadJson }) {
return
{useHero(heroContent, load).hero.title}
;
}
const block = (data: unknown) => {
const script = document.createElement('script');
script.type = 'application/json';
script.id = 'cms-data';
script.textContent = JSON.stringify(data);
document.body.append(script);
};
afterEach(() => {
document.getElementById('cms-data')?.remove();
vi.useRealTimers();
});
describe('useHero', () => {
it('takes the hero of the data block and asks nothing', async () => {
block({ hero: answer('Van de host') });
const load = vi.fn();
await renderWithProviders();
await waitFor(() =>
expect(screen.getByTestId('title')).toHaveTextContent(
'Van de host',
),
);
expect(load).not.toHaveBeenCalled();
});
it('keeps the baked hero when the block has no usable one', async () => {
block({ hero: { title: 'x' } });
await renderWithProviders(()} />);
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
});
it('asks the API without a block and shows a usable answer', async () => {
const load = vi.fn().mockResolvedValue(answer('Van de API'));
await renderWithProviders();
await waitFor(() =>
expect(screen.getByTestId('title')).toHaveTextContent('Van de API'),
);
expect(load.mock.calls[0][0]).toBe('/api/v1/hero');
});
it('keeps the baked hero on a 204, an error or an unusable answer', async () => {
for (const load of [
vi.fn().mockResolvedValue(undefined),
vi.fn().mockRejectedValue(new Error('status 500')),
vi.fn().mockResolvedValue({ title: 'x' }),
]) {
const { unmount } = await renderWithProviders(
,
);
await waitFor(() => expect(load).toHaveBeenCalled());
await Promise.resolve();
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
unmount();
}
});
it('gives up after the time-out', async () => {
vi.useFakeTimers();
const load = vi.fn(
(_path, signal) =>
new Promise((_resolve, reject) =>
signal.addEventListener('abort', () =>
reject(new Error('aborted')),
),
),
);
await renderWithProviders();
await vi.advanceTimersByTimeAsync(8001);
expect(load.mock.calls[0][1].aborted).toBe(true);
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
});
});