Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
Created June 30, 2020 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisDobby/8c853d43f98139462ba7de11fb75260d to your computer and use it in GitHub Desktop.
Save ChrisDobby/8c853d43f98139462ba7de11fb75260d to your computer and use it in GitHub Desktop.
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