Skip to content

Instantly share code, notes, and snippets.

@samselikoff
Created April 27, 2020 22:55
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 samselikoff/d1dfba7bf3a352a5b05273dcae8f101d to your computer and use it in GitHub Desktop.
Save samselikoff/d1dfba7bf3a352a5b05273dcae8f101d to your computer and use it in GitHub Desktop.
import { useSearch } from "use-cloudinary";
import { Server, Response } from "miragejs";
import { render, screen } from "@testing-library/react";
function App() {
const [search, data, status] = useSearch({ endpoint: "/example-endpoint" });
if (status === "loading") return <p data-test-id="loading">Loading...</p>;
if (status === "error") return <p data-test-id="error">Error</p>;
return (
<>
{data.resources.map((resource) => (
<p data-test-id={`resource-${resouce.id}`} key={resource.id}>
{resource.value}
</p>
))}
</>
);
}
// use-search.test.js
test('the status is "loading" while the request is in flight', async () => {
let sendResponse;
let server = new Server({
routes() {
this.get("/example-endpoint", () => {
return new Promise((resolve) => {
sendResponse = resolve;
});
});
},
});
render(<App />);
expect(await screen.findByTestId("loading")).toBeVisible();
// Send response + clean up
sendResponse();
server.shutdown();
});
test('the status is "error" if the server responds with an error', async () => {
let server = new Server({
routes() {
this.get("/example-endpoint", () => new Response(500));
},
});
render(<App />);
expect(await screen.findByTestId("error")).toBeVisible();
// Clean up
server.shutdown();
});
test("the data renders on success", async () => {
let server = new Server({
routes() {
this.get("/example-endpoint", () => ({
resources: [
{ id: 1, value: "A" },
{ id: 2, value: "B" },
{ id: 3, value: "C" },
],
}));
},
});
render(<App />);
await waitForElementToBeRemoved(screen.findByTestId("loading"));
expect(await screen.findByTestId("resource-1")).toBeVisible();
expect(await screen.findByTestId("resource-2")).toBeVisible();
expect(await screen.findByTestId("resource-3")).toBeVisible();
// Clean up
server.shutdown();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment