Testing GraphQL Queries with Apollo Client

Mocked Provider

export const SPEAKERSQUERY = gql`
query speakers {
speakers {
id
name
bio
sessions {
id
title
}
featured
}
}
`;

Install Packages

Imports

import { MockedProvider } from "@apollo/client/testing";
import { mount } from "enzyme";
import { Speakers, SPEAKERSQUERY } from "./Speakers";
import React from "react";
import { act } from "react-dom/test-utils";
import wait from "waait";

Mock data for query

const mockSpeakerData = {
request: {
query: SPEAKERSQUERY,
},
result: {
data: {
speakers: [
{
id: "1234",
name: "Adhithi Ravichandran",
bio: "Here is my bio",
sessions: [
{
id: "1233",
title: "GraphQL Testing",
},
{
id: "2345",
title: "GraphQL Big picture",
},
],
featured: false,
},
],
},
},
};

Test Happy Path

it("renders speaker data", async () => {
let wrapper;
await act(async () => {
wrapper = mount(
<MockedProvider addTypename={false} mocks={[mockSpeakerData]}>
<Speakers />
</MockedProvider>
);
});

await act(() => wait(0));
wrapper.update();
expect(wrapper).toBeTruthy();
expect(wrapper.find(".panel-heading")).toHaveText(
"Speaker: Adhithi Ravichandran"
);
expect(wrapper.find(".panel-body")).toHaveText(
"Bio: Here is my bio"
);
});

MockedProvider parameters:

wait()

Assertions

Test Loading Speakers

it("renders loading speaker", () => {
let wrapper;
act(() => {
wrapper = mount(
<MockedProvider addTypename={false} mocks={[mockSpeakerData]}>
<Speakers />
</MockedProvider>
);
});

expect(wrapper).toBeTruthy();
expect(wrapper).toHaveText("Loading speakers...");
});

Test Errors

const mockErrorData = {
request: {
query: SPEAKERSQUERY,
},
error: new Error("Network Error"),
};
it("renders with error", async () => {
let wrapper;
await act(async () => {
wrapper = mount(
<MockedProvider addTypename={false} mocks={[mockErrorData]}>
<Speakers />
</MockedProvider>
);
});

await act(() => wait(0));
expect(wrapper).toBeTruthy();
expect(wrapper).toHaveText("Error loading speakers!");
});
const mockGraphQLErrorData = {
request: {
query: SPEAKERSQUERY,
},
result: {
errors: [new GraphQLError('Error!')],
data: {
// ....
}
},
};

Resources and Talk

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adhithi Ravichandran

Software Consultant, Author, Speaker, React Native|React|GraphQL|Cypress Dev & Indian Classical Musician