diff --git a/docs/source/development-testing/testing.mdx b/docs/source/development-testing/testing.mdx index 06a69d5db25..9821626749c 100644 --- a/docs/source/development-testing/testing.mdx +++ b/docs/source/development-testing/testing.mdx @@ -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" } diff --git a/src/testing/react/__tests__/MockedProvider.test.tsx b/src/testing/react/__tests__/MockedProvider.test.tsx index 8dd2b3be043..eb18f3b3a9f 100644 --- a/src/testing/react/__tests__/MockedProvider.test.tsx +++ b/src/testing/react/__tests__/MockedProvider.test.tsx @@ -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"; @@ -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(query, { variables }); + + if (loading || data === undefined) return

Loading the user ID...

; + + return

The user ID is '{data.user.id}'

; + } + + const mocks: ReadonlyArray = [ + { + delay: 30, // prevent React from batching the loading state away + request: { + query, + variables, + }, + result: { data: { user } }, + }, + ]; + + render( + + + + ); + + 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(query, { variables }); + + if (loading || data === undefined) return

Loading the user ID...

; + + return

The user ID is '{data.user.id}'

; + } + + const mocks: ReadonlyArray = [ + { + delay: Infinity, // keep loading forever. + request: { + query, + variables, + }, + }, + ]; + + render( + + + + ); + + expect( + await screen.findByText("Loading the user ID...") + ).toBeInTheDocument(); + }); }); describe("@client testing", () => {