Search code examples
reactjsreact-testing-library

How to test an input that stores/updates the value in React state


This the component I am trying to unit test with React testing library

export const TextInput = ({ label, inputValue, setInputValue }) => {
  return (
    <form>
      <label>
        {label}
        <input
          type="text"
          value={inputValue}
          onChange={(event) => {
            setInputValue(event.target.value);
          }}
        />
      </label>
    </form>
  );
};

useState is used in the parent component and passed in to as props.

How do i render this when it depends on the useState hook


Solution

  • The answer is probably this.

    import { render, fireEvent } from "@testing-library/react";
    import { describe, expect, it } from "vitest";
    import TextInput from "../../src/case/TextInput";
    
    describe("TextInput", () => {
      it("work", () => {
        let inputValueOnFirstRender = undefined;
        let isCallbackCalled = false;
    
        const inputValue = 0;
        const setInputValue = () => {
          isCallbackCalled = true;
        };
    
        const { getByRole } = render(
          <TextInput inputValue={inputValue} setInputValue={setInputValue} />
        );
    
        inputValueOnFirstRender = getByRole("textbox").value;
    
        fireEvent.change(getByRole("textbox"), { target: { value: "1" } });
    
        expect(inputValueOnFirstRender).toBe("0");
        expect(isCallbackCalled).toBe(true);
      });
    });
    

    But at least what assertion do you want?

    Exactly what functionality do you want to test?