Skip to content

Commit

Permalink
Add delay in docs for loading state testing (apollographql#11287)
Browse files Browse the repository at this point in the history
  • Loading branch information
gzm0 authored Oct 17, 2023
1 parent 7d3cac9 commit 89374ca
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
3 changes: 3 additions & 0 deletions docs/source/development-testing/testing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,9 @@ We can use the asynchronous `screen.findByText` method to query the DOM elements
```jsx
it("should render dog", async () => {
const dogMock = {
delay: 30 // to prevent React from batching the loading state away
// delay: Infinity // if you only want to test the loading state

request: {
query: GET_DOG_QUERY,
variables: { name: "Buck" }
Expand Down
66 changes: 65 additions & 1 deletion src/testing/react/__tests__/MockedProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react";
import { DocumentNode } from "graphql";
import { render, waitFor } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import gql from "graphql-tag";

import { itAsync, MockedResponse, MockLink } from "../../core";
Expand Down Expand Up @@ -708,6 +708,70 @@ describe("General use", () => {
}).then(resolve, reject);
}
);

it("should support loading state testing with delay", async () => {
function Component({ username }: Variables) {
const { loading, data } = useQuery<Data, Variables>(query, { variables });

if (loading || data === undefined) return <p>Loading the user ID...</p>;

return <p>The user ID is '{data.user.id}'</p>;
}

const mocks: ReadonlyArray<MockedResponse> = [
{
delay: 30, // prevent React from batching the loading state away
request: {
query,
variables,
},
result: { data: { user } },
},
];

render(
<MockedProvider mocks={mocks}>
<Component {...variables} />
</MockedProvider>
);

expect(
await screen.findByText("Loading the user ID...")
).toBeInTheDocument();
expect(
await screen.findByText("The user ID is 'user_id'")
).toBeInTheDocument();
});

it("should support loading state testing with infinite delay", async () => {
function Component({ username }: Variables) {
const { loading, data } = useQuery<Data, Variables>(query, { variables });

if (loading || data === undefined) return <p>Loading the user ID...</p>;

return <p>The user ID is '{data.user.id}'</p>;
}

const mocks: ReadonlyArray<MockedResponse> = [
{
delay: Infinity, // keep loading forever.
request: {
query,
variables,
},
},
];

render(
<MockedProvider mocks={mocks}>
<Component {...variables} />
</MockedProvider>
);

expect(
await screen.findByText("Loading the user ID...")
).toBeInTheDocument();
});
});

describe("@client testing", () => {
Expand Down

0 comments on commit 89374ca

Please sign in to comment.