component is like: <Button and <Icon are customized components which wrap up the <button and <icon


const handleToggleShow = useCallback(() => {
    setShow(!show);
}, [show]);

const displayUI = (
    <div>
        <Icon
            testId="editIcon"
            onClick={handleToggleShow}
            className="edit-icon"
        >
    </div>
);

const editUI = (
 <form data-testid="form" onSubmit={handleSubmit}
    <InputComponent /> 
    <Button 
        testId="saveButton"
        text="Save"
        disabled={...}
        size="large"
        color="blue"
        type="submit"
    />
    <Button
        testId="cancelButton"
        text="Cancel"
        disabled={...}
        size="large"
        color="grey"
        onClick={handleClickCancel}
    />
 </form>
);


return(
<div>
    {show ? editUI}
    {!show? displayUI}
</div>
);

Test is like:

test("show render edit ui when click button", () => {
    render(<A {...props} />)
    const icon = screen.getByTestId("editIcon");
    expect(icon).toBeInDocument();

    fireEvent.click(element);
    const form = screen.getByTestId("form"); 
   //here throws error: unable to find an element by [data-testid="form"]
    expect(form).toBeInDocument();
});

Then I tried queryByTestId("form") and tried getByTestId("saveButton"), it throws error "received value must be an HTMLElement or as an SVGElement",

I was thinking maybe icon click event was not triggered, then I ran this test, still got error

test("show render edit ui when click button", () => {
    const handleToggleShow = jest.fn();
    render(<A {...props} />)
    const icon = screen.getByTestId("editIcon");
    expect(icon).toBeInDocument();

    fireEvent.click(element);
    expect(handleToggleShow).toHaveBeenCalled(); //received number of calls 0
});

Anyone can help? why getByTestId or queryByTestId is not working

1

There are 1 best solutions below

1
On

Update here: In the previous test, I didn't pass any mock props to the component. after passing props, the issue somehow fixed.