App.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from './App';
const BUTTON = 'button';
const CHECKBOX = 'checkbox';
test('button has correct initial color', () => {
render(<App />);
// Find an element with a role of button and text 'Change to blue'
const colorButton = screen.getByRole(BUTTON, { name: 'Change to blue'}) // name = displayed text
// Expect the background color to be red
expect(colorButton).toHaveStyle({ backgroundColor: 'red'})
// Click the button
userEvent.click(colorButton);
// Expect the background color to be blue
expect(colorButton).toHaveStyle({ backgroundColor: 'blue'})
// Expect the button text to be 'Change to red'
expect(colorButton.toHaveTextContent).toBe('Change to red');
});
test('Initial conditions', () => {
render(<App />);
// Check that the button starts out enabled
const colorButton = screen.getByRole(BUTTON, { name: 'Change to blue'});
expect(colorButton).toBeEnabled();
// Check that the checkbox starts unchecked
const checkbox = screen.getByRole(CHECKBOX);
expect(checkbox).not.toBeChecked();
});
test('Checkbox disables button on first click and enables on second click', () => {
render(<App />);
// Checks when checkbox is checked, button is disabled
const checkbox = screen.getByRole(CHECKBOX, { name: 'Disable button' });
const colorButton = screen.getByRole(BUTTON, { name: 'Change to blue' });
userEvent.click(checkbox);
expect(colorButton).toBeDisabled();
// Checks when checkbox is unchecked, button is enabled
userEvent.click(checkbox);
expect(colorButton).toBeEnabled();
});