React testing library – testing a button

Hi, in this post we are going to test a button with react testing library also the methodology will be the “Regression testing” this means that first we are going to create the test and finally we are going to create our react component (button).

So first the 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')
})

To run the test open your terminal and run:

npm test

Finally create the component:

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>
    </div>
  )
}

export default App

Finally:

Jest dom

Roles

Links:

By Cristina Rojas.