Uladz Kha
Uladz Kha

Reputation: 2354

How to test condition rendered elements with react testing library

I'm trying to cover my functionality with test, i have the image input:

<input
    data-testid="fileuploadtestid"
    type="file"
    accept="image/*"
    capture="camera"
    onChange={uploadImage}
/>

On change method checks if file provided and creates the link;

const uploadImage = (e) => {
    const { files } = e.target;

    if (files?.length) {
      const url = URL.createObjectURL(files[0]);

      setImageUrl(url);
    } else {
      setImageUrl("");
    }
  };

Based on imageUrl value image renders conditionally:

{imageUrl && (
    <img
      data-testid="prevtestid"
      className="preview_img"
      src={imageUrl}
      alt={imageUrl}
      crossOrigin="anonymous"
      ref={imageRef}
     />
  )}

And i want to check if it renders correctly using react testing library to get the image element I use data-testid="prevtestid":

test("renders learn react link", async () => {
  const { container, rerender } = render(<Home />);
  global.URL.createObjectURL = jest.fn();
  const file = new File(["(⌐□_□)"], "pug.png", { type: "image/png" });

  const input = screen.getByTestId("fileuploadtestid");
  fireEvent.change(input, { target: { files: [file] } });

  rerender(<Home />);
expect(screen.getByTestId("prevtestid")).toBeInTheDocument();
}
);

I attached the latest version what have i tried to implement, i tried to use waitFor, rerender, render in various ways but i'm getting the same error all time: Unable to find an element by: [data-testid="prevtestid"].

Please tell me how can i test it ?

Upvotes: 0

Views: 456

Answers (1)

Emmanuel Ponnudurai
Emmanuel Ponnudurai

Reputation: 1074

The mock that you are creating is not really returning anything. You should return a url so that the components get's an imageUrl and is then able to show the <img /> element.

global.URL.createObjectURL = jest.fn().mockReturnValueOnce('https://www.samplerandomdomain.com/images/123.jpg');

Upvotes: 1

Related Questions