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 4 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 `reuse` field to a number indicating how many times the mock should be reused:

<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" }
}
},
reuse: 2, // The mock can be reused twice before it's removed, default is 0
alessbell marked this conversation as resolved.
Show resolved Hide resolved
}
];
```

</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
8 changes: 7 additions & 1 deletion 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>>;
reuse?: number;
error?: Error;
delay?: number;
newData?: ResultFunction<FetchResult>;
Expand Down Expand Up @@ -127,7 +128,12 @@ ${unmatchedVars.map((d) => ` ${stringifyForDisplay(d)}`).join("\n")}
);
}
} else {
mockedResponses.splice(responseIndex, 1);
if (!response.reuse) {
alessbell marked this conversation as resolved.
Show resolved Hide resolved
mockedResponses.splice(responseIndex, 1);
} else if (response.reuse !== Number.POSITIVE_INFINITY) {
alessbell marked this conversation as resolved.
Show resolved Hide resolved
response.reuse--;
}


const { newData } = response;
if (newData) {
Expand Down
99 changes: 99 additions & 0 deletions src/testing/react/__tests__/MockedProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,105 @@ describe("General use", () => {
expect(errorThrown).toBeFalsy();
});

it('should reuse mocks when instructed to', async () => {
alessbell marked this conversation as resolved.
Show resolved Hide resolved
let isLoaded = false;
let isError = false;
alessbell marked this conversation as resolved.
Show resolved Hide resolved
function Component({ username }: Variables) {
const { loading, error } = useQuery<Data, Variables>(query, { variables: { username }, fetchPolicy: 'network-only' });
if (!loading) {
if (error) {
isError = true;
}
isLoaded = true;
}
return null;
}
alessbell marked this conversation as resolved.
Show resolved Hide resolved

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

const mockLink = new MockLink(mocks, true, { showWarnings: false });

const Wrapper = ({ children }: { children: React.ReactNode }) => <MockedProvider link={mockLink}>{children}</MockedProvider>
const reset = () => {
isLoaded = false;
isError = false;
}
const waitForLoaded = async () => {
await waitFor(() => {
expect(isLoaded).toBe(true);
expect(isError).toBe(false);
});
}
const waitForError = async () => {
await waitFor(() => {
expect(isLoaded).toBe(true);
expect(isError).toBe(true);
});
}

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

rerender(<Component username="mock_username2" />);
await waitForLoaded();
reset();

rerender(<Component username="mock_username3" />);
await waitForLoaded();
reset();

rerender(<Component username="mock_username" />);
await waitForLoaded();
reset();

rerender(<Component username="mock_username2" />);
await waitForLoaded();
reset();

rerender(<Component username="mock_username3" />);
await waitForError();
reset();

rerender(<Component username="mock_username" />);
await waitForError();
reset();

rerender(<Component username="mock_username2" />);
await waitForLoaded();
reset();
});

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