0

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 ?

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.