Ashwin Allen
Ashwin Allen

Reputation: 99

React Testing Library - how to set initial value of state variable

i have the following react counter application

import { useState } from 'react';

const Counter = () => {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <button
        onClick={() => {
          setCounter((value) => value + 1 );
        }}
        type='button'
        value={`${counter}`}
      >
       {counter}
      </button>
      <button
        disabled={counter > 2 ? false : true}
        type='button'
        value={`${counter}`}
        data-testid='counterBtn'
      >
        Exit
      </button>
    </div>
  );
};

export default Counter;

now i want to test the application by setting the initial value of the counter greater than 2 in my test case and check if the button is enabled. How can i set the initial value of the counter for the below test case?

  it('Enable button if counter is greater than 2'), () => {
      const { getByTestId } = CounterRender();
      const btn = getByTestId('counterBtn');
      expect(getByTestId('counterBtn')).toBeEnabled();
  };

Upvotes: 1

Views: 6014

Answers (2)

pritam
pritam

Reputation: 2558

The main principle of react-testing-library is to test the how your web pages are interacted by the users and not the implementation details.

So, you can write a test to simulate a click on your button, making the state to increment to 2. And then assert if the button is disabled. (since this is the way user will interact with your component)

You can use fireEvent or userEvent (recommended) for simulating the clicks.

    const { getByTestId } = CounterRender();
    const btn = getByTestId('counterBtn');
    
    // simulate click with userEvent
    userEvent.click(btn); // counter will be 1 after this
    userEvent.click(btn); // counter will be 2 after this

    // your assertion here
    expect(getByTestId('counterBtn')).toBeEnabled();

Upvotes: 2

Bryan Goh
Bryan Goh

Reputation: 22

The easiest way is to set your useState counter to 2.

  const [counter, setCounter] = useState(2);

Upvotes: -1

Related Questions