0

I am new to react testing. I have a child component (to which I have no edit access) which is a table along with search box option. It has a event onSearchChange which will update the state with text if value entered in search box. Then we have logic for search using that text. Both set state and search logic is in parent component on which child is rendered. Its working perfectly fine in real time, but in unit testing I am not sure why the onSearchChange is not updating the state(number of rows in table) when I change the value of search box.

This onSearchChange is of type
onSearchChange?: (e: React.SyntheticEvent, value: string) => void;

I have also tried firevents and userevent.type. But nothing works. I have code coverage problem because of this since I need to cover code of search logic.

Please help. Thank you !

Parent Component

const [searchText, setSearchText] = useState("");
//logic to perform search
return(<div className="patient-list">
         <div className="table">
         <SearchTable onSearchChange={(e) => {
         setSearchText((e.target as HTMLInputElement).value)}} table={result} />
         </div>
       </div>
)

test file

it("should search the table", () => {
    const { container } = render(<ParentComponent />);
    let searchInputBox = screen.getByPlaceholderText ("Search the results") as HTMLInputElement
    act(() => {
      searchBoxInput.value = "Age";
      ReactTestUtils.Simulate.change(searchBoxInput);
      const rows = container.getElementsByClassName("class1")
      expect(rows).toHaveLength(6);
    });
  });
  • you can consider state to be black box information. i think a better approach would be to test the component renders correctly in different scenarios. it shouldn't matter what the underlying state is if the render is correct. – Mulan Apr 08 '22 at 16:25
  • @Mulan thank you ! But actually we have search logic method which will be called whenever there is a change in state of search text. Currently this method is not covered under unit testing. This affects code coverage :( – veerragahv Apr 08 '22 at 17:07
  • right, so in your test you target the search element, input a query, and check that the search results are rendered. there's no need to test internal state – Mulan Apr 08 '22 at 18:30
  • @Mulan, yes in real time, if I type in input box, results are populating as per text entered. But if I try to fire change event in test, its not calling onSearchChange in children component. So the expected results are not rendered. This onSearchChange is of type (e: React.SyntheticEvent, value: string) => void; So I am looking for a way to call onSearchChange as a synthetic event with value of HtmlInputElement(search box) in my test. – veerragahv Apr 08 '22 at 19:52

0 Answers0