Search code examples
reactjsjestjsreact-testing-library

how to test onChange write a test for a functional component jest + react testing library


I can't write a test for this line, it says that it is not covered, how can I write a test for this line?

  onChange={({ target: { value } }) => setTestData(value)}

file

import React, { useState } from "react";
    
    import OutlinedInput from "@mui/material/OutlinedInput";
    
    const Test = () => {
      const [testdata, setTestData] = useState<any>("");
    
      const [, setTestData2] = useState<boolean>(false);
    
      return (
        <OutlinedInput
          placeholder="Test"
          value={testdata}
          onChange={({ target: { value } }) => setTestData(value)}
        />
      );
    };
    
    export default Test;

jest

import React from "react";

import { render } from "@testing-library/react";

import Test from ".";

describe("Test", () => {
  test("test1", () => {
    const { container } = render(<Test />);

    expect(container).toBeInTheDocument();
  });
});

Solution

  • You can use fireEvent to trigger the change event on the input box.

    Select the input box and then fire the event like below :

     const input = screen.getByRole('input', {name : ''}); // this is sample one , you need to add the role and name value based on what you have.
    
     fireEvent.change(input, {target: {value: 'a'}})
    
    

    Then you can validate if state is updated or not.

    Read more about fireEvent here.