I'm the author of graphql-codegen-mock-builder, a plugin for GraphQL Code Generator. You point it at a GraphQL schema and it writes typed mock factories, one per schema type, or one per fragment and operation. Each factory fills its fields with @faker-js/faker calls and takes an overrides object, so a test can pin the one field it cares about. It's published on npm as v0.4.1, under the MIT license.
This post covers what the plugin generates, using real output instead of a made-up example. It also covers the one thing it can't fix for you (some cycles in a schema), and how this site runs the real, unmodified plugin inside your browser on the Mock Builder Playground.
If you use GraphQL with TypeScript, you already get types from the schema. Test data is a different story. Without a generator, it's hand-written: someone types { id: "1", title: "Test", author: { ... } } into a test, the schema gains a required field, and every copy of that object has to be found and fixed by hand.
The schema already knows every type, every field and every nullability. So the factories can be generated from it, type-checked against the same types your app uses, and regenerated whenever the schema changes.
In the default schema mode, the plugin writes one factory for every object, input object, interface and union type. Each one returns a full object of that type. Faker runs when you call the factory, not when the code is generated, so every call gives fresh data. overrides is spread last, so it always wins.
Values are picked in this order:
- Field-name heuristics:
idgets a UUID,emailan email,namea full name,titlea sentence,bodya paragraph, a field ending inAta recent date. - The
scalarsmap for custom scalars.DateTimehas a default; you can add your own. - A fallback by type:
Stringis a random word,Inta random integer, and so on. - Object, input, interface and union fields call the nested factory. Enums use the first value, unless you set
enumsAsRandom.
Interfaces and unions delegate to their first implementation or member, in alphabetical order. Types and fields come out alphabetically too, so a regenerated file diffs cleanly.
Schema-mode factories return the whole schema type. But components usually receive a fragment, which is a subset. With mode: "operations", the plugin walks each selection set instead and writes a factory per fragment and per operation. It's meant to sit in a near-operation-file block next to typescript-operations. A fragment UserCard gets mockUserCard(), typed to exactly the fields it selected. Queries and mutations get mock<Name>Query() and mock<Name>Mutation().
The generated code imports types from the standard typescript plugin, so the two run side by side. The minimal config from the README:
schema: schema.graphql
generates:
src/generated/types.ts:
plugins:
- typescript
src/generated/mocks.ts:
plugins:
- graphql-codegen-mock-builder
config:
typesFile: './types'The generated file imports @faker-js/faker, so your project needs faker installed (v9 or v10).
This is the Blog preset from the playground. The output below isn't hand-written for the post: it's copied from the file the site's build generates by running plugin v0.4.1 in Node with the default options.
type Query {
posts(first: Int = 10): [Post!]!
post(slug: String!): Post
}
type Post {
id: ID!
slug: String!
title: String!
body: String!
status: PostStatus!
publishedAt: DateTime
author: Author!
comments: [Comment!]!
}
enum PostStatus {
DRAFT
PUBLISHED
}
type Author {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Comment {
id: ID!
body: String!
author: Author
createdAt: DateTime!
}
scalar DateTimeThe plugin writes four factories:
/* eslint-disable */
// Generated by graphql-codegen-mock-builder. Do not edit manually.
import { faker } from '@faker-js/faker';
import type { Author, Comment, Post, PostStatus, Query } from './types';
export function mockAuthor(overrides?: Partial<Author>): Author {
return {
__typename: 'Author',
email: faker.internet.email(),
id: faker.string.uuid(),
name: faker.person.fullName(),
posts: [],
...overrides,
};
}
export function mockComment(overrides?: Partial<Comment>): Comment {
return {
__typename: 'Comment',
author: null,
body: faker.lorem.paragraph(),
createdAt: faker.date.recent().toISOString(),
id: faker.string.uuid(),
...overrides,
};
}
export function mockPost(overrides?: Partial<Post>): Post {
return {
__typename: 'Post',
author: mockAuthor(),
body: faker.lorem.paragraph(),
comments: [],
id: faker.string.uuid(),
publishedAt: faker.date.recent().toISOString(),
slug: faker.lorem.word(),
status: "DRAFT" as PostStatus,
title: faker.lorem.sentence(),
...overrides,
};
}
export function mockQuery(overrides?: Partial<Query>): Query {
return {
__typename: 'Query',
post: mockPost(),
posts: Array.from({ length: 2 }, () => mockPost()),
...overrides,
};
}A few things worth noticing:
slughas no heuristic, so it falls back to a random word.publishedAtis aDateTime, which uses the built-in scalar default.statusis the first enum value,DRAFT, every time. WithenumsAsRandomon, the factory picks a random value with faker at call time instead.Query.postsis a list of two posts (the defaultlistLength), butAuthor.postsandPost.commentsare empty, andComment.authorisnull. That's the cycle handling, next.
In a test, you call the factory and override what matters:
const post = mockPost({ status: "PUBLISHED" as PostStatus, comments: [mockComment()] });Real schemas are full of cycles. A post has an author, the author has posts, each post has comments, each comment has an author. A naive generator would have mockPost call mockAuthor, which calls mockPost, forever.
With terminateCircularRelationships on (the default), the plugin looks at the type graph. For any field whose type can lead back to the type that contains it:
- a circular list field becomes
[] - a circular nullable field becomes
null - a circular non-null, non-list field still calls the nested factory
That explains the Blog output. Author.posts and Post.comments are lists that lead back, so they're []. Comment.author is nullable and leads back through Author.posts, so it's null. Post.author is non-null and not a list, so mockPost still calls mockAuthor(). That's safe, because mockAuthor cuts its own posts. Query.posts gets two real posts, because nothing leads back to Query.
If every field around a cycle is non-null and not a list, there's nothing safe to cut:
type A { b: B! }
type B { a: A! }An empty list or null would break the types, so the plugin emits the calls, and the factories recurse forever when called. The code generation itself never loops: the cycle check runs on the type graph, and factories reference each other by name. The README documents the limit. The fixes are to make one field in the cycle nullable or a list, or to pass that field in overrides. Operations mode doesn't have this problem, because a selection set is finite.
The playground shows the code but never runs it, so a recursive factory wouldn't crash anything. It would still be wrong to show a preset whose code can't run. So the agent that built the presets added a check that mirrors the plugin's call graph. If a preset has a cycle of calls that are always made, the content build fails with a message like "these factories would call each other forever: A.b → B.a → A (make one field nullable or a list)". The cases above are unit tests.
The Independent level of this site used to be a different idea. I replaced it with a playground for the plugin, and the spec asks for the real published package, pinned exactly, not a lookalike. The site is built by a team of Claude Code agents I direct. A frontend agent ran a spike first (task F8) to see whether the plugin could run in the browser within the level's chunk budget. The agents did the bundling work and the measurements below.
The plugin is a plain function, plugin(schema, documents, config), that returns a string of TypeScript. It doesn't need @graphql-codegen/cli, which is Node-only. Its files import no fs, path, process or Buffer, so it bundles for the browser with no polyfills. The island builds the schema with graphql-js and calls the plugin directly:
plugin(buildASTSchema(parse(sdl)), [], { typesFile: "./types", ...options });That's the same as buildSchema(sdl), split in two so syntax errors keep their line and column for the editor.
What it doesn't do: run the generated code (that would mean shipping faker and a TypeScript compiler) or run the typescript plugin for the types. The playground says both.
The plugin is CommonJS and calls require("graphql"). graphql-js checks that a schema came from the same copy of the library that's using it. If the app code imports graphql from a deep path, the bundler pulls in a second copy, and the plugin rejects the schema: "Cannot use GraphQLObjectType … from another module or realm".
It costs bytes too. In the spike, the chunk was 56,150 B gzipped with one copy and 99,826 B with two, over the level's 90 KB budget. The rule in the code is now: import graphql only as bare from "graphql". Then the client build resolves both sides to the same ESM build, and Node resolves both to CommonJS.
Vitest is the exception: it splits the instances on its own, so tests that call the plugin mock graphql with the CommonJS copy.
The no-JavaScript view and the poster show output generated at build time in Node. The live editor generates in the browser. Those have to match, or the page would show two different answers. The spike compared them by sha256 on three schemas, with the default options and with every option flipped, and they were identical. Browser and Node now go through the same generateMocks() function. A unit test checks that the committed outputs match what that function writes today, and QA's end-to-end test compares the browser output with the plain Node call on the three presets plus a schema none of them has.
The shipped chunk is 58,660 B gzipped, and the stage page doesn't request it until you activate the level or focus the editor. In the spike, warm generation on a large schema took 1.4 ms median, and 5.7 ms with the CPU throttled 4x. The editor waits 250 ms after you stop typing, and the target is updated output within 300 ms for schemas up to 4,000 characters.
- Timing was measured on an Apple M1 Pro with emulated CPU throttling. QA's emulated result was 257 ms after typing stopped at 4x, but the check on a real mid-range phone hasn't been done yet.
- The playground runs schema mode only. Operations mode works in the same browser setup (the spike checked one fragment, two queries and a mutation), but there's no UI for it.
- The site is live now, but the production check covered the pages loading, not the playground running in a visitor's browser. It hasn't been tried in Safari or in Windows Chrome or Edge yet.