Listings Springer/React Testing

Listing 1: Unit-Test der Answers-Komponente
import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';
import Answers from './Answers';

describe('Answers', () => {
    let container: HTMLDivElement;

    beforeEach(() => {
      container = document.createElement('div');
      document.body.appendChild(container);
    });

    afterEach(() => {
      unmountComponentAtNode(container);
      container.remove();
    });

    it('should work', () => {
      const answers = [{ id: 1, answer: 'A' }, { id: 2, answer: 'B' }];

      act(() => {
        render(
          <Answers
            answers={answers}
            correct={1}
            answered={null}
            onAnswer={(id: number) => {}}
          />,
          container
        );
      });

      const buttons = container.querySelectorAll('button');

      expect(buttons).toHaveLength(2);
      expect(buttons[0].textContent).toBe('A');
      expect(buttons[1].textContent).toBe('B');
    });
});

-----

Listing 2: Erweiterung des Unit-Tests mit der React Testing Library
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import Answers from './Answers';

describe('Answers with react testing library', () => {
    afterEach(cleanup);

    it('should render', () => {
      const answers = [{ id: 1, answer: 'A' }, { id: 2, answer: 'B' }];
      const { getAllByTestId } = render(
        <Answers
          answers={answers}
          correct={1}
          answered={null}
          onAnswer={(id: number) => {}}
        />
      );

      const buttons = getAllByTestId('answer-button');
      expect(buttons).toHaveLength(2);
      expect(buttons[0].textContent).toBe('A');
      expect(buttons[1].textContent).toBe('B');
    });
});

-----

Listing 3: Einfügen der Test-ID
<button
    key={answer.id}
    style={style}
    onClick={() => onAnswer(answer.id)}
    data-testid="answer-button"
>
    {answer.answer}
</button>;

-----

Listing 4: Spies im Einsatz
it('should click on a button', () => {
    const onAnswerCallback = jest.fn();
    const { getByText } = render(
      <Answers
        answers={answers}
        correct={1}
        answered={null}
        onAnswer={onAnswerCallback}
      />
    );
    fireEvent.click(getByText('B'));

    expect(onAnswerCallback).toHaveBeenCalledTimes(1);
    expect(onAnswerCallback).toHaveBeenCalledWith(2);
});

-----

Listing 5: Cypress-Test der Quizapplikation
describe('Answer', () => {
    it('should answer a single question correctly', () => {
      cy.visit('http://localhost:3000/quiz/1');

      cy.contains('Lautstärke misst man in...?');

      cy.contains('Dezibel')
        .click()
        .should('have.css', 'background-color')
        .and('equal', 'rgb(0, 128, 0)');
    });
});


