← Wszystkie zadaniaReact · Middle

Akordeon

Napisz komponent Accordion, który dostaje tablicę items z obiektów { title, content }. Każda pozycja ma przycisk z tekstem title, a pod nim content, gdy pozycja jest otwarta.

Na początku wszystkie pozycje są zamknięte. Naraz otwarta jest tylko jedna: otwarcie pozycji zamyka inną, a ponowne kliknięcie zamyka bieżącą. Przycisk ma aria-expanded ze stanem pozycji.

Testy (4)

  1. const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }];
    render(<Accordion items={items} />);
    expect(screen.queryByText('A1')).toBe(null);
    expect(screen.queryByText('A2')).toBe(null);
    expect(screen.getByRole('button', { name: 'Q1' }).getAttribute('aria-expanded')).toBe('false');
  2. const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }];
    render(<Accordion items={items} />);
    fireEvent.click(screen.getByRole('button', { name: 'Q1' }));
    expect(screen.getByText('A1')).toBeTruthy();
    expect(screen.getByRole('button', { name: 'Q1' }).getAttribute('aria-expanded')).toBe('true');
  3. const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }];
    render(<Accordion items={items} />);
    fireEvent.click(screen.getByRole('button', { name: 'Q1' }));
    fireEvent.click(screen.getByRole('button', { name: 'Q2' }));
    expect(screen.getByText('A2')).toBeTruthy();
    expect(screen.queryByText('A1')).toBe(null);
  4. const items = [{ title: 'Q1', content: 'A1' }];
    render(<Accordion items={items} />);
    fireEvent.click(screen.getByRole('button', { name: 'Q1' }));
    fireEvent.click(screen.getByRole('button', { name: 'Q1' }));
    expect(screen.queryByText('A1')).toBe(null);