Skip to content

Instantly share code, notes, and snippets.

@LionelB5
Last active March 10, 2025 19:28
Show Gist options
  • Save LionelB5/ab354f856f898c060d88edd29353597e to your computer and use it in GitHub Desktop.
Save LionelB5/ab354f856f898c060d88edd29353597e to your computer and use it in GitHub Desktop.
Apollo Client V3 link that supports mocking GraphQL subscriptions, mutations and queries. Particularly useful when testing components that rely on queries/mutations that execute concurrently to subscriptions that must be mocked.
import { MockedProvider, MockedResponse } from "@apollo/client/testing";
import { act } from "@testing-library/react";
import { FOO_QUERY } from "../queries";
import MockedLink from "../MockedLink";
describe("example", () => {
test("example usage", async () => {
// simulate requests or mutations
const mocks: MockedResponse[] = [
{ request: { query: FOO_QUERY }, result: { data: { foo: "FOO_DATA" } } },
];
const link = new MockedLink(mocks);
render(
<MockedProvider link={link}>
<ComponentUnderTest />
</MockedProvider>,
);
// simulate subscription operation receiving data
await act(() => {
link.simulateSubscriptionResult({
result: { data: { onBar: "barData" } },
operationName: "BarSubscription",
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment