The code is in project #287 - Testing React and Typescript - part 1
import { render, screen, waitForElementToBeRemoved, } from '@testing-library/react'; import SummaryForm from 'pages/summary/SummaryForm'; import userEvent from '@testing-library/user-event'; const BUTTON = 'button'; const CHECKBOX = 'checkbox'; test('Checkbox is unchecked by default, button is disabled', () => { render(<SummaryForm />); const checkbox = screen.getByRole(CHECKBOX, { name: /terms and conditions/i, }); expect(checkbox).not.toBeChecked(); const confirmOrderButton = screen.getByRole(BUTTON, { name: /confirm order/i, }); expect(confirmOrderButton).toBeDisabled(); }); test('Checkbox enables button on the first click and disables button on second click', () => { render(<SummaryForm />); const checkbox = screen.getByRole(CHECKBOX, { name: /terms and conditions/i, }); const confirmOrderButton = screen.getByRole(BUTTON, { name: /confirm order/i, }); userEvent.click(checkbox); expect(checkbox).toBeChecked(); expect(confirmOrderButton).toBeEnabled(); userEvent.click(checkbox); expect(checkbox).not.toBeChecked(); expect(confirmOrderButton).toBeDisabled(); }); test('popover responds to hover', async () => { render(<SummaryForm />); // popover starts out hidden const nullPopover = screen.queryByText( /no ice cream will actually be delivered/i ); expect(nullPopover).not.toBeInTheDocument(); // popover appears upon mouseover of checkbox label const termsAndConditions = screen.getByText(/terms and conditions/i); userEvent.hover(termsAndConditions); const popover = screen.getByText(/no ice cream will actually be delivered/i); expect(popover).toBeInTheDocument(); // popover disappears when we mouse out userEvent.unhover(termsAndConditions); await waitForElementToBeRemoved(() => screen.queryByText(/no ice cream will actually be delivered/i) ); });
import { useState } from 'react'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; import Popover from 'react-bootstrap/Popover'; import OverlayTrigger from 'react-bootstrap/OverlayTrigger'; const popover = ( <Popover id='popover-basic'> <Popover.Content>No ice cream will actually be delivered</Popover.Content> </Popover> ); const checkboxLabel = ( <OverlayTrigger trigger='hover' placement='right' overlay={popover}> <span> I agree to <span style={{ color: 'blue' }}> Terms and conditions</span> </span> </OverlayTrigger> ); const SummaryForm = () => { const [termsChecked, setTermsChecked] = useState(false); return ( <Form> <Form.Group controlId='terms-and-conditions'> <Form.Check type='checkbox' checked={termsChecked} onChange={(e) => setTermsChecked(e.target.checked)} label={checkboxLabel} /> </Form.Group> <Form.Group> <Button type="submit" disabled={!termsChecked} variant='primary'> Confirm order </Button>{' '} </Form.Group> </Form> ); };