Writing mock data for GraphQL tests gets old fast.
You copy a response from the network tab into a mockCountry object. Three weeks later someone adds a field to the fragment. The test still passes, because the mock is typed as any somewhere along the way. Production shows undefined.
In Part 3Mastering GraphQL Fragments in Vue 3: Component-Driven Data FetchingPart 3 of the Vue 3 + GraphQL series: Learn how to use GraphQL fragments with fragment masking to create truly component-driven data fetching in Vue 3. every component got its own fragment, and fragment masking made sure nobody else can read that data. Really nice for the app. But it raises two questions for tests. How do you hand a masked prop to a component? And where does the data come from?
My answer is the mock factory pattern. Codegen writes one function per schema type, like aCountry(), and each function returns a complete object. You override the two fields your test cares about and ignore the rest.
This post is the style guide I follow. First the setup, then eight rules. Each rule has a ❌ and a ✅, and I ran every snippet against the demo app of this series.
| # | Rule |
|---|---|
| 1 | Never write a mock object by hand. Start from a factory. |
| 2 | Override only what the test asserts on. |
| 3 | Write null when you test the empty state. |
| 4 | Give every list item its own key. |
| 5 | Build masked props with fragmentData. |
| 6 | Nest factories, not helpers. |
| 7 | Mock the network with the typed document, not useQuery. |
| 8 | Let the compiler guard the fragment. Run it in CI. |
Versions at the time of writing: graphql-codegen-typescript-mock-data 5.2, @graphql-codegen/client-preset 7, Vitest 5.1, MSW 3.
npm install -D graphql-codegen-typescript-mock-data \
vitest @vitest/browser-playwright vitest-browser-vue playwright msw
npx playwright install chromium
npx msw init public --save
Tests run in a real browser with Vitest browser mode. If that is new to you, read the Vue 3 testing pyramid postVue 3 Testing Pyramid: A Practical Guide with Vitest Browser ModeLearn a practical testing strategy for Vue 3 applications using composable unit tests, Vitest browser mode integration tests, and visual regression testing. first.
// vitest.config.ts
import { defineConfig } from "vitest/config";
import vue from "@vitejs/plugin-vue";
import { playwright } from "@vitest/browser-playwright";
export default defineConfig({
plugins: [vue()],
test: {
setupFiles: ["./src/test/setup.ts"],
browser: {
enabled: true,
headless: true,
provider: playwright(),
instances: [{ browser: "chromium" }],
},
},
});
graphql-codegen-typescript-mock-data is a codegen plugin. It reads the schema and writes one factory function per type. Add two outputs to codegen.ts:
// codegen.ts
const config: CodegenConfig = {
overwrite: true,
schema: "https://countries.trevorblades.com/graphql",
documents: ["src/**/*.vue", "src/queries/**/*.graphql"],
generates: {
"src/gql/": {
preset: "client",
plugins: [],
config: { useTypeImports: true },
},
// New: schema types + factories
"src/gql/schema.ts": {
plugins: ["typescript"],
config: { useTypeImports: true, avoidOptionals: true },
},
"src/gql/mocks.ts": {
plugins: [
{
"typescript-mock-data": {
typesFile: "./schema.ts",
useTypeImports: true,
addTypename: true,
terminateCircularRelationships: true,
},
},
],
},
},
};
Run npm run codegen and you get this in src/gql/mocks.ts:
// simplified
export const aCountry = (
overrides?: Partial<Country>
): { __typename: "Country" } & Country => {
return {
__typename: "Country",
capital: overrides && overrides.hasOwnProperty("capital") ? overrides.capital! : "demum",
code: overrides && overrides.hasOwnProperty("code") ? overrides.code! : "e9a1940c-...",
name: overrides && overrides.hasOwnProperty("name") ? overrides.name! : "amplexus",
// ...every other field of Country
};
};
The plugin writes the default values at codegen time, so they are the same on every run. Nothing is random, so snapshots don’t flake.
Four config lines cost me time, so here is why they exist:
src/gql/schema.ts. The client preset 7 only writes types for your operations. It no longer exports schema types likeCountry. The factories need them, so the plaintypescriptplugin writes them into a second file.avoidOptionals: true. Without it the schema type sayscapital?: string | null, but the fragment type sayscapital: string | null. TypeScript then rejects every factory result withType 'undefined' is not assignable to type 'string | null'.addTypename: true. Apollo’s cache asks for__typenameon every object. The factories include it.terminateCircularRelationships: true. A country has a continent, the continent has countries. Without the flag the factory recurses forever.
The plumbing is four small files. In the first one, MSW answers requests at the network level:
// src/test/worker.ts
import { setupWorker } from "msw/browser";
import { graphql } from "msw/graphql";
export const API_URL = "https://countries.trevorblades.com/graphql";
export const worker = setupWorker();
export const api = graphql.link(API_URL);
// src/test/setup.ts
import { afterEach, beforeAll } from "vitest";
import { worker } from "./worker";
beforeAll(() => worker.start({ onUnhandledFrame: "error", quiet: true }));
afterEach(() => worker.resetHandlers());
Every test gets a fresh Apollo client and a fresh cache, so one test can’t leak data into the next:
// src/test/render.ts
import type { Component } from "vue";
import { render } from "vitest-browser-vue";
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client/core";
import { DefaultApolloClient } from "@vue/apollo-composable";
import { API_URL } from "./worker";
export function renderWithApollo(component: Component) {
const client = new ApolloClient({
link: new HttpLink({ uri: API_URL }),
cache: new InMemoryCache(),
});
return render(component, {
global: { provide: { [DefaultApolloClient]: client } },
});
}
The last file holds the two helpers that every rule below uses. fragmentData builds a masked prop. mockQuery builds an MSW handler. Both check your data against an Unmasked type. I explain why that type exists in rule 7.
// src/test/mock.ts
import type { TypedDocumentNode } from "@graphql-typed-document-node/core";
import { HttpResponse } from "msw";
import type { FragmentType } from "../gql";
import { api } from "./worker";
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;
type Refs<T> = T extends { " $fragmentRefs"?: infer R }
? UnionToIntersection<R[keyof R]>
: unknown;
/** Resolves every fragment spread, so the type lists all fields the server must send. */
export type Unmasked<T> = T extends ReadonlyArray<infer U>
? Array<Unmasked<U>>
: T extends object
? { [K in Exclude<keyof T, " $fragmentRefs" | " $fragmentName">]: Unmasked<T[K]> } &
Unmasked<Refs<T>>
: T;
export function fragmentData<TData>(
_fragment: TypedDocumentNode<TData, any>,
data: Unmasked<TData>
) {
return data as FragmentType<TypedDocumentNode<TData, any>>;
}
export function mockQuery<TData extends Record<string, unknown>>(
query: TypedDocumentNode<TData, any>,
data: Unmasked<TData>
) {
return api.query(query, () => HttpResponse.json({ data: data as TData }));
}
That is the setup. Now the rules.
A handwritten object breaks every time the fragment grows. A factory already returns every field.
// ❌ breaks when the fragment gets a new field
const country = {
code: "AT",
name: "Austria",
emoji: "🇦🇹",
capital: "Vienna",
phone: "43",
currency: "EUR",
};
// ✅ still compiles
const country = aCountry({ name: "Austria", capital: "Vienna" });
I tested this. I added native to the card fragment and ran vue-tsc. The handwritten object failed. The factory call compiled without a change.
The factory still catches your mistakes:
// ❌ 'nmae' does not exist in type 'Partial<Country>'
aCountry({ nmae: "Austria" });
// ❌ Type 'number' is not assignable to type 'string'
aCountry({ capital: 42 });
An override says “this value matters for this test”. If you set ten fields, the reader can’t see which two matter.
// ❌ which of these does the test check?
aCountry({
code: "AT",
name: "Austria",
emoji: "🇦🇹",
capital: "Vienna",
phone: "43",
currency: "EUR",
});
// ✅ the test checks the name and the capital
aCountry({ name: "Austria", capital: "Vienna" });
The rule works in both directions. Never assert on a default value. "amplexus" is generated filler and it changes when the plugin changes.
// ❌ asserts on generated filler
await expect.element(screen.getByText("amplexus")).toBeVisible();
// ✅ asserts on the value the test set
await expect.element(screen.getByRole("heading", { name: "Austria" })).toBeVisible();
Factories fill every nullable field with a value. So the null branch of your template never runs unless you ask for it. Ask for it with an explicit null.
test("hides the capital row when the API returns null", async () => {
const country = fragmentData(
CountryCard_CountryFragmentFragmentDoc,
aCountry({ name: "Antarctica", capital: null })
);
const screen = await render(CountryCard, { props: { country } });
await expect.element(screen.getByRole("heading", { name: "Antarctica" })).toBeVisible();
await expect.element(screen.getByText("Capital:")).not.toBeInTheDocument();
});
The plugin has a defaultNullableToNull option that flips the default. I leave it off. A filled object is the common case, and the null in the test tells the reader what the test is about.
The default values are static. Two calls to aCountry() return the same code. If Apollo’s cache normalizes that type, it stores both objects under one key, and your list shows the same item twice.
// ❌ both objects share the default key
countries: [aCountry({ name: "Austria" }), aCountry({ name: "Germany" })];
// renders: Austria, Austria
// ✅ every item has its own key
countries: [
aCountry({ code: "AT", name: "Austria" }),
aCountry({ code: "DE", name: "Germany" }),
];
// renders: Austria, Germany
I reproduced the “Austria, Austria” result with keyFields: ["code"] on the cache. Apollo normalizes every type with an id field by default, so in most schemas you hit this without any config.
CountryCard from Part 3 takes one prop:
interface Props {
country: FragmentType<typeof CountryCard_CountryFragment>;
}
FragmentType is the masked type. You can’t pass a plain object or a raw factory result to it, and that is the point of masking.
// ❌ 'name' does not exist in type '{ " $fragmentRefs"?: ... }'
render(CountryCard, { props: { country: { name: "Austria" } } });
// ❌ no properties in common with the masked type
render(CountryCard, { props: { country: aCountry() } });
// ✅
const country = fragmentData(
CountryCard_CountryFragmentFragmentDoc,
aCountry({ name: "Austria", emoji: "🇦🇹", capital: "Vienna" })
);
render(CountryCard, { props: { country } });
The full test:
// src/components/CountryCard.spec.ts
import { expect, test } from "vitest";
import { render } from "vitest-browser-vue";
import { CountryCard_CountryFragmentFragmentDoc } from "../gql/graphql";
import { aCountry } from "../gql/mocks";
import { fragmentData } from "../test/mock";
import CountryCard from "./CountryCard.vue";
test("shows the country with its capital", async () => {
const country = fragmentData(
CountryCard_CountryFragmentFragmentDoc,
aCountry({ name: "Austria", emoji: "🇦🇹", capital: "Vienna" })
);
const screen = await render(CountryCard, { props: { country } });
await expect.element(screen.getByRole("heading", { name: "Austria" })).toBeVisible();
await expect.element(screen.getByText("Vienna")).toBeVisible();
});
The test needs no Apollo client, no network, and no provider. A component that only reads a fragment is a pure function of its prop.
The helper checks the data against the fragment:
// ❌ wrong type for this fragment: missing emoji, capital, phone, currency
fragmentData(CountryCard_CountryFragmentFragmentDoc, aLanguage());
A fragment can spread another fragment:
fragment CountryWithLanguages_CountryFragment on Country {
code
name
emoji
languages {
...LanguageItem_LanguageFragment
}
}
With the official makeFragmentData you have to wrap every level by hand, from the inside out:
// ❌ Type 'Language' has no properties in common with type '{ " $fragmentRefs"?: ... }'
makeFragmentData(
aCountry({ languages: [aLanguage({ name: "German" })] }),
CountryWithLanguages_CountryFragmentFragmentDoc
);
// ❌ compiles, but nobody wants to write this
const german = makeFragmentData(
aLanguage({ name: "German" }),
LanguageItem_LanguageFragmentFragmentDoc
);
const austria = makeFragmentData(
{ ...aCountry({ name: "Austria" }), languages: [german] },
CountryWithLanguages_CountryFragmentFragmentDoc
);
fragmentData resolves the inner fragment in its type, so you nest factories the way the data is nested:
// ✅ one helper call, nested factories
const austria = fragmentData(
CountryWithLanguages_CountryFragmentFragmentDoc,
aCountry({ name: "Austria", languages: [aLanguage({ name: "German" })] })
);
This is a known gap. There is an open pull request that adds the same idea to makeFragmentData, but nobody merged it. A package called graphql-code-generator-unmask-fragment ships the type from that pull request. Its last release is from 2024, and with the types that client preset 7 generates it resolved to never in my test. So I keep the 15 lines in my repo.
CountryListWithCards calls useQuery and spreads the card fragment:
query CountriesWithDetails {
countries {
code
...CountryCard_CountryFragment
}
}
Don’t mock useQuery. Then your test skips the Apollo client, the cache, and the link. Let the real client run and answer the request with MSW.
And pass the generated document, never the operation name. The document is a TypedDocumentNode, so the helper knows the result type.
// ❌ replaces the composable, so the test skips the client and the cache
vi.mock("@vue/apollo-composable");
// ❌ a string has no type. Any response compiles.
api.query("CountriesWithDetails", () => HttpResponse.json({ data: { nope: 1 } }));
// ✅ typed document + factories
worker.use(
mockQuery(CountriesWithDetailsDocument, {
countries: [
aCountry({ code: "AT", name: "Austria" }),
aCountry({ code: "DE", name: "Germany" }),
],
})
);
The full test file:
// src/components/CountryListWithCards.spec.ts
import { expect, test } from "vitest";
import { HttpResponse } from "msw";
import { CountriesWithDetailsDocument } from "../gql/graphql";
import { aCountry } from "../gql/mocks";
import { mockQuery } from "../test/mock";
import { renderWithApollo } from "../test/render";
import { api, worker } from "../test/worker";
import CountryListWithCards from "./CountryListWithCards.vue";
test("renders a card for every country in the response", async () => {
worker.use(
mockQuery(CountriesWithDetailsDocument, {
countries: [
aCountry({ code: "AT", name: "Austria" }),
aCountry({ code: "DE", name: "Germany" }),
],
})
);
const screen = await renderWithApollo(CountryListWithCards);
await expect.element(screen.getByRole("heading", { name: "Austria" })).toBeVisible();
await expect.element(screen.getByRole("heading", { name: "Germany" })).toBeVisible();
});
test("shows the error message when the API fails", async () => {
worker.use(
api.query(CountriesWithDetailsDocument, () =>
HttpResponse.json({ errors: [{ message: "Countries are down" }] })
)
);
const screen = await renderWithApollo(CountryListWithCards);
await expect.element(screen.getByText("Countries are down")).toBeVisible();
});
For an error there is no data to type, so the second test uses api.query directly.
I want to be honest with you. MSW with the typed document alone does not check the fragment fields. This compiles:
// TypeScript accepts this. The card gets none of its fields.
api.query(CountriesWithDetailsDocument, () =>
HttpResponse.json({ data: { countries: [{ code: "AT" }] } })
);
Look at the generated query type and you see why:
type CountriesWithDetailsQuery = {
countries: Array<
{ code: string } & {
" $fragmentRefs"?: { CountryCard_CountryFragmentFragment: ... };
}
>;
};
The parent only owns code. The fragment fields sit behind an optional $fragmentRefs key, so TypeScript can’t demand them. Masking hides the child’s data from the parent, and it hides it from your mock too.
The Unmasked type from the setup walks the query type and resolves every spread. mockQuery uses it, so the incomplete response fails:
// ❌ Type '{ code: string }' is not assignable to type
// '{ code: string } & { code: string; name: string; emoji: string; ... }'
mockQuery(CountriesWithDetailsDocument, { countries: [{ code: "AT" }] });
Factories have one weakness, and you should know it. A factory gives the component more than its fragment asks for. aCountry() has all 15 fields. The card fragment has 6.
I removed capital from the card fragment and ran everything again:
| Check | Result |
|---|---|
| The tests | all 4 pass, also the one that expects “Vienna” |
vue-tsc on the factory mock | compiles |
vue-tsc on CountryCard.vue | ❌ Property 'capital' does not exist |
The tests stay green because the factory still hands over a capital that the real API would no longer send. Only the compiler sees the problem, and it sees it in the component, not in the test.
So the jobs are split:
| What drifted | Who catches it |
|---|---|
| Fragment and component | vue-tsc, in the component |
| Schema and mock | vue-tsc, in the test, after codegen rewrote the factory |
| Component and behavior | the test |
A passing test run does not show that the fragment selects enough fields. vue-tsc shows that. So both run in CI:
npm run codegen && git diff --exit-code src/gql # the generated code is up to date
npx vue-tsc -b # mocks and fragments match
npx vitest run # the components behave
Two more things to know:
- Circular relationships end in
{} as Country. WithterminateCircularRelationships,aCountry().continent.countries[0]is an empty object that claims to be aCountry. If a test needs that level, pass it as an override. - The helpers do nothing at runtime.
fragmentDatareturns the same object and only changes the type.
I read the docs before I settled on this, and I think it is the right default. Here is what I compared:
| Approach | Good | Bad |
|---|---|---|
| Factories + MSW, as in this post | Real Apollo client and cache run. One factory serves fragment tests and query tests. | You maintain the small Unmasked helper. |
Apollo MockLink | No extra dependency. | Skips the HTTP layer, so the test never runs the link chain or fetch. |
Schema-driven mocks (@apollo/graphql-testing-library) | It resolves the response from the schema, so the response always matches the query. | Overrides are resolvers, not objects. It lists MSW 2 as its peer dependency, and I use MSW 3. |
Apollo’s own testing docs say: “Wherever possible, use MSW: it enables more realistic tests.” So MSW is not a hot take.
One thing will change. Vue Apollo 5 supports Apollo Client’s own data masking, and Apollo Client ships an Unmasked type for it. It is still a beta and needs Apollo Client 4, so this series stays on the client preset masking for now. The rules stay the same in both.
Generate the factories, start every mock from one, and say only what the test is about. fragmentData gets the data into a component with a fragment. mockQuery gets it into a component with a query. The compiler checks that mock, fragment, and schema agree.
Colocated fragments made the components independent in Part 3. With factories the tests are independent too. A leaf component test needs one line of data and never touches the network.
Find the full demo for this series here: example
Note: The code for this tutorial is on the part4 branch.
git clone https://github.com/alexanderop/vue-graphql-simple-example.git
cd vue-graphql-simple-example
git checkout part4
npm install
npx playwright install chromium
npm test