React testing library – testing a checkbox

This is the first part of an example of how to test a checkbox that is also related with a button in React testing library.

First we create our test where we have the button test and also the checkbox test:

// Dependencies
import { render, screen, fireEvent } from '@testing-library/react'
import App from './App'

test('Button has correct initial color', () => {
  render(<App />)

  // Find an element with a role of button & text of 'Change to blue'
  const colorButton = screen.getByRole('button', { name: 'Change to blue' })

  // Expect the background color to be red
  expect(colorButton).toHaveStyle({ backgroundColor: 'red' })

  // Click button
  fireEvent.click(colorButton)

  // Expect
  expect(colorButton).toHaveStyle({ backgroundColor: 'blue' })

  // Expect the button text to be'Change to red'
  expect(colorButton.textContent).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 out unchecked
  const checkbox = screen.getByRole('checkbox')
  expect(checkbox).not.toBeChecked()
})

Then we have the <App /> component that have our button & checkbox:

import { useState } from 'react'
import './App.css'

function App() {
  const [buttonColor, setButtonColor] = useState('red')
  const newButtonColor = buttonColor === 'red' ? 'blue' : 'red'

  return (
    <div className="App">
      <header>
        <h1>My App</h1>
      </header>

      <button
        style={{ backgroundColor: buttonColor }}
        onClick={() => setButtonColor(newButtonColor)}
      >
        Change to {newButtonColor}
      </button>

      <input type="checkbox" />
    </div>
  )
}

export default App

In the next post we are going to create some test where the checkbox is related to the button.

By Cristina Rojas.