techStackGuru

Jest fireEvent Testing


App.js file


function App() {

    const [buttonText, setButtonText] = useState('Button1');
  
    function handleClick(){
      setButtonText('Button2');
    };
  
    return (
      <div className="App">
          <Button data-testid="buttonId" onClick={handleClick}>{buttonText}</Button>
      </div>
    );
  }
  
  export default App;

App.test.js file


test("button click",()=>{
    render(<App />);
    
    const bt = screen.getByTestId("buttonId")
    fireEvent.click(bt);
    expect(bt).toHaveTextContent("Button2");
  })

To Run test we use below command


npm test
jest-test

Example 2

App.js file


function App() {

    const [buttonColor, setButtonColor] = useState('green')
    const newButtonColor = buttonColor === 'green' ? 'blue' : 'green'
  
    return (
      <div className="App">
        <button
          style={{ backgroundColor: buttonColor }}
          onClick={() => setButtonColor(newButtonColor)}
        >
          Switch to {newButtonColor}
        </button>
      </div>
    );
  }
  
  export default App;

App.test.js file


test('Button has correct initial color', () => {
    render(<App />)
  
    // Look for a component with a button role and the text "Switch to blue."
    const colorButton = screen.getByRole('button', { name: 'Switch to blue' })
  
    // You can expect a green background.
    expect(colorButton).toHaveStyle({ backgroundColor: 'green' })
  
    // Click button
    fireEvent.click(colorButton)
  
    // Expect
    expect(colorButton).toHaveStyle({ backgroundColor: 'blue' })
  
    // Expect "Switch to green" to be the button text.
    expect(colorButton.textContent).toBe('Switch to green')
  })
jest-test

previous-button
next-button