리액트 테스팅(3)

jest와 react-testing-library

2022-12-26

fireEvent를 userEvent로 바꿔보기

npm i @testing-library/user-event
test('Checkbox enables button on first click and disableds on second click', async () => {
  const user = userEvent.setup();

  render(<SummaryForm />);

  const checkbox = screen.getByRole('checkbox', {
    name: /terms and conditions/i
  });
  const confirmButton = screen.getByRole('button', {
    name: /confirm order/i
  });

  await user.click(checkbox);
  expect(confirmButton).toBeEnabled();

  await user.click(checkbox);
  expect(confirmButton).toBeDisabled();
});

async/await 으로 비동기 처리해주지 않으면, expect가 먼저 실행되기 때문에 오류가 발생한다


Screen 메소드들 써보기

test('popover responds to hover', async () => {
  const user = userEvent.setup();

  render(<SummaryForm />);

  // popover starts out hidden
  const nullPopover = screen.queryByText(/no ice cream will actually be delivered/i);
  expect(nullPopover).not.toBeInTheDocument();

  // popover appears on mouseover of checkbox label
  const termsAndConditions = screen.getByText(/terms and conditions/i);
  await user.hover(termsAndConditions);
  const popover = screen.getByText(/no ice cream will actually be delivered/i);
  expect(popover).toBeInTheDocument();

  // popover disappears when we mouse out
  await user.unhover(termsAndConditions);
  expect(popover).not.toBeInTheDocument();
});
const popover = (
  <Popover id="popover-basic">
    <Popover.Body>No ice cream will actually be delivered</Popover.Body>
  </Popover>
);

const checkboxLabel = (
  <span>
    I agree to
    <OverlayTrigger trigger={['hover', 'focus']} placement="right" overlay={popover}>
      <span style={{color: 'blue'}}>Terms and Conditions</span>
    </OverlayTrigger>
  </span>
);