Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import * as React from "react";
import { render, RenderResult } from "@testing-library/react";
import fetch from "jest-fetch-mock";
import { useGetAnnotation } from "./useGetAnnotation";
import { act } from "react-dom/test-utils";
fetch.enableMocks();
const presignedUrl = "https:/a-presigned-url";
const testXml = btoa("<something/>");
const TestGet = () => {
const [xmlData, isError, setPresignUrl] = useGetAnnotation();
React.useEffect(() => {
setPresignUrl(presignedUrl);
}, [setPresignUrl]);
return (
<>
<div data-testid="xml-data">{xmlData}</div>
<div data-testid="is-error">{isError.toString()}</div>
</>
);
};
const renderAndWait = async (): Promise<RenderResult> => {
let result;
await act(async () => {
result = render(<TestGet />);
});
return result as RenderResult;
};
const setupFetchSuccess = () => {
fetch.mockResponse(JSON.stringify({ data: testXml }));
};
const setupFetchFail = () => {
fetch.mockResponse("", { status: 500 });
};
afterEach(fetch.resetMocks);
test("should fetch from the supplied presigned url", async () => {
await renderAndWait();
expect(fetch).toHaveBeenCalledWith(presignedUrl);
});
test("should return the fetched data", async () => {
setupFetchSuccess();
const { getByTestId } = await renderAndWait();
const receivedXml = getByTestId("xml-data");
const error = getByTestId("is-error");
expect(receivedXml.textContent).toEqual(atob(testXml));
expect(error.textContent).toEqual("false");
});
test("should return an error if the call failed", async () => {
setupFetchFail();
const { getByTestId } = await renderAndWait();
const error = getByTestId("is-error");
expect(error.textContent).toEqual("true");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.