Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request 241: reuse mocks in MockLink / MockedProvider #11178

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/yellow-flies-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@apollo/client": minor
---

Support re-using of mocks in the MockedProvider
31 changes: 31 additions & 0 deletions docs/source/development-testing/testing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,37 @@ it("renders without error", async () => {

</ExpansionPanel>

#### Reusing mocks

By default, a mock is only used once. If you want to reuse a mock for multiple operations, you can set the `maxUsageCount` field to a number indicating how many times the mock should be used:

<ExpansionPanel title="Click to expand 🐶">

```jsx title="dog.test.js"
import { GET_DOG_QUERY } from "./dog";

const mocks = [
{
request: {
query: GET_DOG_QUERY,
variables: {
name: "Buck"
}
},
result: {
data: {
dog: { id: "1", name: "Buck", breed: "bulldog" }
}
},
maxUsageCount: 2, // The mock can be used twice before it's removed, default is 1
}
];
```

</ExpansionPanel>

Passing `Number.POSITIVE_INFINITY` will cause the mock to be reused indefinitely.

### Setting `addTypename`

In the example above, we set the `addTypename` prop of `MockedProvider` to `false`. This prevents Apollo Client from automatically adding the special `__typename` field to every object it queries for (it does this by default to support data normalization in the cache).
Expand Down
16 changes: 14 additions & 2 deletions src/testing/core/mocking/mockLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface MockedResponse<
> {
request: GraphQLRequest<TVariables>;
result?: FetchResult<TData> | ResultFunction<FetchResult<TData>>;
maxUsageCount?: number;
error?: Error;
delay?: number;
newData?: ResultFunction<FetchResult>;
Expand Down Expand Up @@ -127,8 +128,11 @@ ${unmatchedVars.map((d) => ` ${stringifyForDisplay(d)}`).join("\n")}
);
}
} else {
mockedResponses.splice(responseIndex, 1);

if (response.maxUsageCount! > 1) {
response.maxUsageCount!--;
} else {
mockedResponses.splice(responseIndex, 1);
}
const { newData } = response;
if (newData) {
response.result = newData();
Expand Down Expand Up @@ -195,6 +199,14 @@ ${unmatchedVars.map((d) => ` ${stringifyForDisplay(d)}`).join("\n")}
if (query) {
newMockedResponse.request.query = query;
}

mockedResponse.maxUsageCount = mockedResponse.maxUsageCount ?? 1;
invariant(
mockedResponse.maxUsageCount > 0,
`Mock response maxUsageCount must be greater than 0, %s given`,
mockedResponse.maxUsageCount
);

return newMockedResponse;
}
}
Expand Down
221 changes: 220 additions & 1 deletion src/testing/react/__tests__/MockedProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import React from "react";
import { DocumentNode } from "graphql";
import { render, waitFor } from "@testing-library/react";
import { act, render, waitFor } from "@testing-library/react";
import gql from "graphql-tag";

import { itAsync, MockedResponse, MockLink } from "../../core";
import { MockedProvider } from "../MockedProvider";
import { useQuery } from "../../../react/hooks";
import { InMemoryCache } from "../../../cache";
import { ApolloLink } from "../../../link/core";
import { QueryResult } from "../../../react/types/types";

const variables = {
username: "mock_username",
Expand Down Expand Up @@ -55,6 +56,10 @@ interface Data {
};
}

interface Result {
current: QueryResult<any, any> | null
}

interface Variables {
username: string;
}
Expand Down Expand Up @@ -481,6 +486,220 @@ describe("General use", () => {
expect(errorThrown).toBeFalsy();
});

it('Uses a mock a configured number of times when `maxUsageCount` is configured', async () => {
const result: Result = { current: null };
function Component({ username }: Variables) {
result.current = useQuery<Data, Variables>(query, { variables: { username } });
return null;
}

const waitForLoaded = async () => {
await waitFor(() => {
expect(result.current?.loading).toBe(false);
expect(result.current?.error).toBeUndefined();
});
}

const waitForError = async () => {
await waitFor(() => {
expect(result.current?.error?.message).toMatch(/No more mocked responses/);
});
}

const refetch = () => {
return act(async () => {
try {
await result.current?.refetch();
} catch { }
});
}

const mocks: ReadonlyArray<MockedResponse> = [
{
request: {
query,
variables: {
username: 'mock_username'
}
},
maxUsageCount: 2,
result: { data: { user } }
},
];

const mockLink = new MockLink(mocks, true, { showWarnings: false });
const link = ApolloLink.from([errorLink, mockLink]);
const Wrapper = ({ children }: { children: React.ReactNode }) => <MockedProvider link={link}>{children}</MockedProvider>

render(<Component username="mock_username" />, { wrapper: Wrapper });
await waitForLoaded();
await refetch();
await waitForLoaded();
await refetch();
await waitForError();
});

it('Uses a mock infinite number of times when `maxUsageCount` is configured with Number.POSITIVE_INFINITY', async () => {
const result: Result = { current: null };
function Component({ username }: Variables) {
result.current = useQuery<Data, Variables>(query, { variables: { username } });
return null;
}

const waitForLoaded = async () => {
await waitFor(() => {
expect(result.current?.loading).toBe(false);
expect(result.current?.error).toBeUndefined();
});
}

const refetch = () => {
return act(async () => {
try {
await result.current?.refetch();
} catch { }
});
alessbell marked this conversation as resolved.
Show resolved Hide resolved
}

const mocks: ReadonlyArray<MockedResponse> = [
{
request: {
query,
variables: {
username: 'mock_username'
}
},
maxUsageCount: Number.POSITIVE_INFINITY,
result: { data: { user } }
},
];

const mockLink = new MockLink(mocks, true, { showWarnings: false });
const link = ApolloLink.from([errorLink, mockLink]);
const Wrapper = ({ children }: { children: React.ReactNode }) => <MockedProvider link={link}>{children}</MockedProvider>

render(<Component username="mock_username" />, { wrapper: Wrapper });
await waitForLoaded();
await refetch();
await waitForLoaded();
await refetch();
await waitForLoaded();
sebakerckhof marked this conversation as resolved.
Show resolved Hide resolved
});

it('uses a mock once when `maxUsageCount` is not configured', async () => {
const result: Result = { current: null };
function Component({ username }: Variables) {
result.current = useQuery<Data, Variables>(query, { variables: { username } });
return null;
}

const waitForLoaded = async () => {
await waitFor(() => {
expect(result.current?.loading).toBe(false);
expect(result.current?.error).toBeUndefined();
});
}

const waitForError = async () => {
await waitFor(() => {
expect(result.current?.error?.message).toMatch(/No more mocked responses/);
});
}

const refetch = () => {
return act(async () => {
try {
await result.current?.refetch();
} catch { }
});
}

const mocks: ReadonlyArray<MockedResponse> = [
{
request: {
query,
variables: {
username: 'mock_username'
}
},
result: { data: { user } }
},
];

const mockLink = new MockLink(mocks, true, { showWarnings: false });
const link = ApolloLink.from([errorLink, mockLink]);
const Wrapper = ({ children }: { children: React.ReactNode }) => <MockedProvider link={link}>{children}</MockedProvider>

render(<Component username="mock_username" />, { wrapper: Wrapper });
await waitForLoaded();
await refetch();
await waitForError();
});

it('can still use other mocks after a mock has been fully consumed', async () => {
const result: Result = { current: null };
function Component({ username }: Variables) {
result.current = useQuery<Data, Variables>(query, { variables: { username } });
return null;
}

const waitForLoaded = async () => {
await waitFor(() => {
expect(result.current?.loading).toBe(false);
expect(result.current?.error).toBeUndefined();
});
}

const refetch = () => {
return act(async () => {
try {
await result.current?.refetch();
} catch { }
});
}

const mocks: ReadonlyArray<MockedResponse> = [
{
request: {
query,
variables: {
username: 'mock_username'
}
},
maxUsageCount: 2,
result: { data: { user } }
},
{
request: {
query,
variables: {
username: 'mock_username'
}
},
result: {
data: {
user: {
__typename: 'User',
id: 'new_id'
}
}
}
},
];

const mockLink = new MockLink(mocks, true, { showWarnings: false });
const link = ApolloLink.from([errorLink, mockLink]);
const Wrapper = ({ children }: { children: React.ReactNode }) => <MockedProvider link={link}>{children}</MockedProvider>

render(<Component username="mock_username" />, { wrapper: Wrapper });
await waitForLoaded();
await refetch();
await waitForLoaded();
await refetch();
await waitForLoaded();
expect(result.current?.data?.user).toEqual({ __typename: 'User', id: 'new_id' });
});

it('should return "Mocked response should contain" errors in response', async () => {
let finished = false;
function Component({ ...variables }: Variables) {
Expand Down