android-logo

Jest Button Testing

Table of Content

  • Test Button Label
  • Test Button Click
  • Test Button Disabled
  • Test Button Enabled

Here we will see how to test Button using Jest.

Test Button Label

App.js file


import React from 'react'; 
import { Button } from 'react-bootstrap'

let buttonText = 'Button1'

function App() {

  return (
    <div className="App">
        <Button data-testid="buttonId" >{buttonText}</Button>
    </div>
  );
}

export default App;


it("renders button correctly",()=>{
    render(<App />);
    const bt = screen.getByTestId("buttonId")
    expect(bt).toHaveTextContent("Button1");
  })

To Run test we use below command


npm test

jest-test

Test Button Click

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

Test Button Disabled

App.js file


function App() {

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

App.test.js file


test("button type",()=>{
    render(<App />);
    const bt = screen.getByTestId("buttonId")
    expect(bt).toBeDisabled();
  })

Run test


npm test

jest-test

Test Button Enabled

App.js file


function App() {

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

App.test.js file


test("button type",()=>{
    render(<App />);
    const bt = screen.getByTestId("buttonId")
    expect(bt).not.toBeDisabled(); 
  })

Run test


npm test

jest-test

previous-button
next-button