Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

graphql-codegen-typescript-mock-data

ardeois440.2kMIT5.0.0TypeScript support: included

GraphQL Codegen plugin for building mock data

graphql, codegen, graphql-codegen, plugin, typescript, mocks, fakes

readme

graphql-codegen-typescript-mock-data

Description

GraphQL Codegen Plugin for building mock data based on the schema.

Installation

yarn add -D graphql-codegen-typescript-mock-data

Configuration

typesFile (string, defaultValue: null)

Defines the file path containing all GraphQL types. This file can also be generated through graphql-codegen

useTypeImports(boolean, defaultValue: false)

Will use import type {} rather than import {} when importing only types. This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option

addTypename (boolean, defaultValue: false)

Adds __typename property to mock data

enumsAsTypes (boolean, defaultValue: false)

Changes enums to TypeScript string union types

includedTypes (string[], defaultValue: undefined)

Specifies an array of types to include in the mock generation. When provided, only the types listed in this array will have mock data generated.

Example:

plugins:
  - typescript-mock-data:
      includedTypes:
        - User
        - Avatar

excludedTypes (string[], defaultValue: undefined)

Specifies an array of types to exclude in the mock generation. When provided, the types listed in this array will not have mock data generated.

Example:

plugins:
  - typescript-mock-data:
      excludedTypes:
        - User
        - Avatar

terminateCircularRelationships (boolean | 'immediate', defaultValue: false)

When enabled, prevents circular relationships from triggering infinite recursion. After the first resolution of a specific type in a particular call stack, subsequent resolutions will return an empty object cast to the correct type.

When enabled with immediate, it will only resolve the relationship once, independently of the call stack. Use this option if you're experiencing out of memory errors while generating mocks.

prefix (string, defaultValue: a for consonants & an for vowels)

The prefix to add to the mock function name. Cannot be empty since it will clash with the associated typescript definition from @graphql-codegen/typescript

listElementCount (number, defaultValue: 1)

How many elements should be generated for lists. For example, with listElementCount: 3 a schema field names: [String!]! would generate 3 names in each mock.

enumValues (string, defaultValue: change-case-all#pascalCase)

Changes the case of the enums. The format of the converter must be a valid module#method. You can also use keep to keep all GraphQL names as-is. Available case functions in change-case-all are camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, lowerCase, localeLowerCase, lowerCaseFirst, spongeCase, titleCase, upperCase, localeUpperCase and upperCaseFirst See more

typeNames (string, defaultValue: change-case-all#pascalCase)

Changes the case of types. The format of the converter must be a valid module#method. You can also use keep to keep all GraphQL names as-is. Available case functions in change-case-all are camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, lowerCase, localeLowerCase, lowerCaseFirst, spongeCase, titleCase, upperCase, localeUpperCase and upperCaseFirst See more

scalars ({ [Scalar: string]: GeneratorOptions | InputOutputGeneratorOptions }, defaultValue: undefined)

Allows you to define mappings for your custom scalars. Allows you to map any GraphQL Scalar to a casual embedded generator (string or function key) with optional arguments, or a or faker generator with optional arguments

For detailed configuration options, see GeneratorOptions documentation.

Examples using casual

plugins:
  - typescript-mock-data:
      scalars:
        Date: date # gets translated to casual.date()

With arguments

plugins:
  - typescript-mock-data:
      scalars:
        Date: # gets translated to casual.date('YYYY-MM-DD')
          generator: date
          arguments: 'YYYY-MM-DD'

Examples using faker

plugins:
  - typescript-mock-data:
      scalars:
        Date: date.past # gets translated to faker.date.past()

With arguments

plugins:
  - typescript-mock-data:
      scalars:
        Date: # gets translated to faker.date.past(10)
          generator: date.past
          arguments: 10

Custom value generator

plugins:
  - add: "import { arrayBufferGenerator } from '../generators';"
  - typescript-mock-data:
      scalars:
        ArrayBuffer: arrayBufferGenerator()

typesPrefix (string, defaultValue: '')

Useful if you have globally exported types under a certain namespace. e.g If the types file is something like this

declare namespace Api {
 type User {
  ...
 }
}

Setting the typesPrefix to Api. will create the following mock data

export const aUser = (overrides?: Partial<Api.User>): Api.User => {

enumsPrefix (string, defaultValue: '')

Similar to typesPrefix, but for enum types

declare namespace Api {
 enum Status {
  ...
 }
}

Setting the enumsPrefix to Api. will create the following mock data

export const aUser = (overrides?: Partial<User>): User => {
   status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Api.Status.Online,
}

typeNamesMapping ({ [typeName: string]: string }, defaultValue: {})

Allows you to define mappings to rename the types. This is useful when you want to override the generated type name. For example, if you have a type called User and you want to rename it to RenamedUser you can do the following:

plugins:
  - typescript-mock-data:
      typesFile: '../generated-types.ts'
      typeNamesMapping:
        User: RenamedUser

This will generate the following mock function:

export const aUser = (overrides?: Partial<RenamedUser>): RenamedUser => {

Note: It is not possible to rename your enums using this option.

transformUnderscore (boolean, defaultValue: true)

When disabled, underscores will be retained for type names when the case is changed. It has no effect if typeNames is set to keep.

dynamicValues (boolean, defaultValue: false)

When enabled, values will be generated dynamically when the mock function is called rather than statically when the mock function is generated. The values are generated consistently from a casual seed that can be manually configured using the generated seedMocks(seed: number) function, as shown in this test.

useImplementingTypes (boolean, defaultValue: false)

When enabled, it will support the useImplementingTypes GraphQL codegen configuration.

  • When a GraphQL interface is used for a field, this flag will use the implementing types, instead of the interface itself.

defaultNullableToNull (boolean, defaultValue: false)

When enabled, it will set all nullable fields to null per default instead of generating a value.

fieldGeneration ({ [typeName: string]: { [fieldName: string]: GeneratorOptions } }, defaultValue: undefined)

This setting allows you to add specific generation to a field for a given type. For example if you have a type called User and a field called birthDate you can override any generated value there as follows:

plugins:
  - typescript-mock-data:
      scalars:
        Date: date.future
      fieldGeneration:
        User:
          birthDate: date.past

Note that even if birthDate is a scalar of Date type, its value will still be overridden.

If you want to use a specific generator for all fields of a given name, you can declare it under a property called _all:

plugins:
  - typescript-mock-data:
      scalars:
        Date: date.future
      fieldGeneration:
        _all:
          email: internet.email
        AdminUser:
          email: 'admin@email.com'

In the above example all resolvers with the name email will use the internet.email generator. However since we specified a specific email for AdminUser that will take precedence over the _all generated value.

For detailed configuration options, see GeneratorOptions documentation.

generateLibrary ('casual' | 'faker', defaultValue: 'faker')

Select a library to generate mock values. The default is faker, Other options include casual casual is not maintained and will be remove in future major versions. faker is useful when you want to use a mock function with the dynamicValues option enabled in the browser.

GeneratorOptions type

This type is used in scalars and fieldGeneration options.

Examples using faker

With arguments

plugins:
  - typescript-mock-data:
      scalars:
        Date: # gets translated to faker.date.past(10)
          generator: date.past
          arguments: 10

With multiple arguments

plugins:
  - typescript-mock-data:
      scalars:
        Description: # gets translated to faker.lorem.paragraphs(3, '\n')
          generator: lorem.paragraphs
          arguments:
            - 3
            - '\n'

Shorthand if you don't have arguments

plugins:
  - typescript-mock-data:
      scalars:
        Date: date.past # gets translated to faker.date.past()

With extra function call

fieldName: # gets translated to faker.date.past().toLocaleDateString()
  generator: date.past
  extra:
    function: toLocaleDateString

With extra function call arguments

fieldName: # gets translated to faker.date.past().toLocaleDateString('en_GB)
  generator: date.past
  extra:
    function: toLocaleDateString
    arguments: 'en_GB'

Custom value generator

# gets translated as is
fieldName: arrayBufferGenerator()

Examples using casual (deprecated)

Shorthand if you don't have arguments

fieldName: date # gets translated to casual.date()

With arguments

fieldName: # gets translated to casual.date('YYYY-MM-DD')
  generator: date
  arguments: 'YYYY-MM-DD'

With multiple arguments

fieldName: # gets translated to casual.integer(-100, 100)
  generator: integer
  arguments:
    - -100
    - 100

With extra function call

fieldName: # gets translated to casual.integer.toFixed()
  generator: integer
  extra:
    function: toFixed

With extra function call arguments

fieldName: # gets translated to casual.integer.toFixed(3)
  generator: integer
  extra:
    function: toFixed
    arguments: 3

InputOutputGeneratorOptions type

This type is used in the scalars option. It allows you to specify different GeneratorOptions for input and output types for your scalars, in the same way the typescript-operations plugin does.

So, using the first example of the previous section, you can specify a string for your input and a Date for your output:

plugins:
  - typescript-mock-data:
      scalars:
        Date:
          input: date.weekday # Date fields in input objects will be mocked as strings
          output:
            generator: date.past # Date fields in other GraphQL types will be mocked as JS Dates
            arguments: 10

Examples of usage

codegen.yml

overwrite: true
schema: schema.graphql
generates:
  src/generated-types.ts:
    plugins:
      - 'typescript'
  src/mocks/generated-mocks.ts:
    plugins:
      - typescript-mock-data:
          typesFile: '../generated-types.ts'
          enumValues: upper-case#upperCase
          typeNames: keep
          scalars:
            AWSTimestamp: number.int # gets translated to faker.number.int()

With eslint-disable rule

codegen.yml

overwrite: true
schema: schema.graphql
generates:
  src/generated-types.ts:
    plugins:
      - 'typescript'
  src/mocks/generated-mocks.ts:
    plugins:
      - add:
          content: '/* eslint-disable @typescript-eslint/no-use-before-define,@typescript-eslint/no-unused-vars,no-prototype-builtins */'
      - typescript-mock-data:
          typesFile: '../generated-types.ts'
          enumValues: upper-case#upperCase
          typeNames: keep
          scalars:
            AWSTimestamp: number.int # gets translated to faker.number.int()

Example of generated code

Given the following schema:

scalar AWSTimestamp

type Avatar {
  id: ID!
  url: String!
}

type User {
  id: ID!
  login: String!
  avatar: Avatar
  status: Status!
  updatedAt: AWSTimestamp
}

type Query {
  user: User!
}

input UpdateUserInput {
  id: ID!
  login: String
  avatar: Avatar
}

enum Status {
  ONLINE
  OFFLINE
}

type Mutation {
  updateUser(user: UpdateUserInput): User
}

The code generated will look like:

export const anAvatar = (overrides?: Partial<Avatar>): Avatar => {
  return {
    id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '0550ff93-dd31-49b4-8c38-ff1cb68bdc38',
    url: overrides && overrides.hasOwnProperty('url') ? overrides.url! : 'aliquid',
  };
};

export const anUpdateUserInput = (overrides?: Partial<UpdateUserInput>): UpdateUserInput => {
  return {
    id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '1d6a9360-c92b-4660-8e5f-04155047bddc',
    login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'qui',
    avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : anAvatar(),
  };
};

export const aUser = (overrides?: Partial<User>): User => {
  return {
    id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 'a5756f00-41a6-422a-8a7d-d13ee6a63750',
    login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'libero',
    avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : anAvatar(),
    status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Status.Online,
    updatedAt: overrides && overrides.hasOwnProperty('updatedAt') ? overrides.updatedAt! : 1458071232,
  };
};

Usage in tests

Those helper functions can be used in our unit tests:

const user = aUser({ login: 'johndoe' });

// will create a user object with `login` property overridden to `johndoe`

Dealing with Timezone

If some properties use generated dates, the result could different depending on the timezone of your machine.

To force a timezone, you can set environment variable TZ:

TZ=UTC graphql-codegen

This will force the timezone to UTC, whatever the timezone of your machine or CI

Contributing

Feel free to open issues and pull requests. We always welcome support from the community.

To run this project locally:

  • Use Node >= 18
  • Make sure that you have the latest Yarn version (https://yarnpkg.com/lang/en/docs/install/)
  • Clone this repo using git clone
  • Run yarn
  • Run yarn build to build the package
  • Run yarn test to make sure everything works

License

GitHub license

MIT

changelog

v5.0.0 (Thu Jun 26 2025)

💥 Breaking Change

Authors: 1


v4.4.0 (Thu Apr 03 2025)

🚀 Enhancement

  • feature(scalars): support distinction between input and output generator configs #182 (@argvniyx-enroute)

Authors: 1


v4.3.2 (Wed Feb 26 2025)

🐛 Bug Fix

Authors: 2


v4.3.1 (Wed Feb 26 2025)

🐛 Bug Fix

Authors: 2


v4.3.0 (Wed Feb 26 2025)

🚀 Enhancement

Authors: 2


v4.2.0 (Thu Feb 06 2025)

🚀 Enhancement

Authors: 1


v4.1.0 (Fri Sep 20 2024)

🚀 Enhancement

Authors: 2


v4.0.1 (Thu Sep 12 2024)

🐛 Bug Fix

Authors: 1


v4.0.0 (Wed Sep 04 2024)

💥 Breaking Change

  • feat: update and use faker as default generator #169 (@ardeois)

Authors: 1


v3.8.0 (Fri May 17 2024)

🚀 Enhancement

  • feat(terminateCircularRelationships): Add 'immediate' as a value for the terminateCircularRelationships option #161 (@rpereira-anchor)

Authors: 1


v3.7.2 (Wed Apr 17 2024)

🐛 Bug Fix

Authors: 1


v3.7.1 (Thu Dec 21 2023)

🐛 Bug Fix

  • fix: type error when using typesPrefix and terminateCircularRelationships #151 (@Miyaboom)

Authors: 1


v3.7.0 (Mon Nov 27 2023)

🚀 Enhancement

Authors: 1


v3.6.0 (Fri Nov 17 2023)

🚀 Enhancement

Authors: 2


v3.5.4 (Fri Nov 17 2023)

🐛 Bug Fix

  • fix: Error when using useImplementingTypes and terminateCircularRelationships at the same time #141 (@Swanoo @ardeois)

Authors: 2


v3.5.3 (Fri Nov 17 2023)

🐛 Bug Fix

Authors: 2


v3.5.2 (Fri Nov 17 2023)

🐛 Bug Fix

Authors: 1


v3.5.1 (Thu Oct 12 2023)

🐛 Bug Fix

Authors: 1


v3.5.0 (Wed Apr 19 2023)

🚀 Enhancement

  • implement defaultNullableToNull config option (#128) #130 (@gurschitz)

Authors: 1


v3.4.2 (Wed Apr 19 2023)

🐛 Bug Fix

Authors: 1


v3.4.1 (Thu Apr 13 2023)

🐛 Bug Fix

Authors: 1


v3.4.0 (Tue Apr 11 2023)

🚀 Enhancement

Authors: 1


v3.3.1 (Tue Mar 21 2023)

🐛 Bug Fix

  • fix: relationships overrides via fieldGeneration config #123 (@gurschitz)

Authors: 1


v3.3.0 (Thu Mar 16 2023)

🚀 Enhancement

Authors: 1


v3.2.2 (Thu Feb 02 2023)

🐛 Bug Fix

Authors: 2


v3.2.1 (Wed Feb 01 2023)

🐛 Bug Fix

  • Updated readme to reflect the renaming of typenames to typeNames #112 (@lkloeppel)

Authors: 1


v3.2.0 (Fri Jan 27 2023)

🚀 Enhancement

Authors: 2


v3.1.1 (Thu Jan 26 2023)

🐛 Bug Fix

Authors: 1


v3.1.0 (Thu Jan 26 2023)

🚀 Enhancement

Authors: 2


v3.0.0 (Thu Jan 26 2023)

💥 Breaking Change

Authors: 2


v2.7.1 (Mon Jan 09 2023)

🐛 Bug Fix

Authors: 1


v2.7.0 (Wed Dec 07 2022)

🚀 Enhancement

  • fix(enumValues): update behaviour to match typescript plugin #103 (@ardeois)

Authors: 1


v2.6.0 (Thu Nov 17 2022)

🚀 Enhancement

Authors: 1


v2.5.2 (Thu Sep 29 2022)

🐛 Bug Fix

Authors: 1


v2.5.1 (Thu Sep 29 2022)

🐛 Bug Fix

  • fix: custom generator for native scalars #95 (@ardeois)

Authors: 1


v2.5.0 (Thu Sep 29 2022)

🚀 Enhancement

Authors: 2


v2.4.1 (Thu Sep 29 2022)

🐛 Bug Fix

  • fix: listElementCount sometimes undefined #94 (@ardeois)

Authors: 1


v2.4.0 (Mon Sep 19 2022)

🚀 Enhancement

Authors: 1


v2.3.0 (Mon Sep 19 2022)

🚀 Enhancement

Authors: 1


(Thu Jul 28 2022)

🔩 Dependency Updates

Authors: 1


v2.2.4 (Wed Jul 27 2022)

🐛 Bug Fix

Authors: 1


v2.2.3 (Tue Apr 12 2022)

🐛 Bug Fix

Authors: 1


v2.2.2 (Tue Apr 12 2022)

🐛 Bug Fix

Authors: 1


(Mon Mar 21 2022)

🐛 Bug Fix

Authors: 1


v2.2.0 (Mon Mar 21 2022)

🚀 Enhancement

Authors: 2


v2.1.4 (Fri Mar 04 2022)

🐛 Bug Fix

Authors: 1


v2.1.3 (Fri Mar 04 2022)

🐛 Bug Fix

Authors: 1


v2.1.2 (Fri Feb 18 2022)

🐛 Bug Fix

Authors: 2


v2.1.1 (Fri Feb 18 2022)

⚠️ Pushed to main

Authors: 1


v2.1.0 (Fri Feb 18 2022)

🚀 Enhancement

Authors: 2


v2.0.0 (Thu Nov 04 2021)

💥 Breaking Change

Authors: 1


v1.8.5 (Mon Oct 25 2021)

🐛 Bug Fix

Authors: 2


v1.8.4 (Mon Oct 25 2021)

🐛 Bug Fix

Authors: 1


v1.8.3 (Wed Oct 20 2021)

🐛 Bug Fix

Authors: 1


v1.8.1 (Wed Oct 20 2021)

⚠️ Pushed to master

Authors: 1


v1.8.0 (Wed Oct 20 2021)

🚀 Enhancement

Authors: 1


v1.7.2 (Tue Sep 21 2021)

🐛 Bug Fix

Authors: 1


v1.7.1 (Tue Sep 07 2021)

🐛 Bug Fix

Authors: 1


v1.7.0 (Tue Sep 07 2021)

🚀 Enhancement

  • fix: generate Query and Mutation mocks #57 (@ardeois)

Authors: 1


v1.6.0 (Tue Sep 07 2021)

🚀 Enhancement

Authors: 1


v1.5.10 (Tue Sep 07 2021)

🐛 Bug Fix

  • fix(typesPrefix): use typesPrefix in imports #55 (@ardeois)

Authors: 1


(Tue Sep 07 2021)

🔩 Dependency Updates

Authors: 1


v1.5.8 (Tue Sep 07 2021)

🐛 Bug Fix

Authors: 1


v1.5.7 (Wed Jun 23 2021)

🐛 Bug Fix

Authors: 2


(Thu Jun 10 2021)

🔩 Dependency Updates

Authors: 1


(Thu Jun 10 2021)

🔩 Dependency Updates

Authors: 1


v1.5.4 (Wed May 12 2021)

🐛 Bug Fix

Authors: 1


v1.5.3 (Tue May 11 2021)

🐛 Bug Fix

Authors: 1


v1.5.2 (Tue May 11 2021)

🐛 Bug Fix

Authors: 1


v1.5.1 (Tue Apr 13 2021)

🐛 Bug Fix

Authors: 1


v1.5.0 (Mon Apr 12 2021)

🚀 Enhancement

Authors: 1


v1.4.1 (Wed Mar 31 2021)

🐛 Bug Fix

Authors: 1


v1.4.0 (Thu Jan 28 2021)

🚀 Enhancement

🐛 Bug Fix

Authors: 3


v1.3.4 (Thu Oct 15 2020)

🐛 Bug Fix

Authors: 1


(Tue Oct 13 2020)

🐛 Bug Fix

Authors: 1


(Tue Oct 13 2020)

🐛 Bug Fix

Authors: 1


v1.3.1 (Tue Oct 13 2020)

🐛 Bug Fix

Authors: 1


v1.3.0 (Tue Oct 13 2020)

🚀 Enhancement

Authors: 1


v1.2.1 (Thu Sep 24 2020)

⚠️ Pushed to master

Authors: 1


v1.2.0 (Thu Sep 24 2020)

🚀 Enhancement

  • feat(scalars): add support for custom scalar with arguments #30 (@ardeois)

Authors: 1


v1.1.0 (Mon Aug 10 2020)

🚀 Enhancement

Authors: 1


(Fri Jul 17 2020)

🐛 Bug Fix

Authors: 1


v1.0.0 (Tue Jul 14 2020)

💥 Breaking Change

  • feat: use indefinite to find the correct article #26 (@ardeois)

Authors: 1


v0.5.0 (Tue Jul 14 2020)

🚀 Enhancement

  • feat: add scalars config option for custom GraphQL [scalar -> casual] mappings #21 (@3nvi @ardeois)

Authors: 2


v0.4.2 (Tue Jul 14 2020)

🐛 Bug Fix

  • feat: allow users to specify the prefix of mock builders #25 (@3nvi)

Authors: 1

  • Aggelos Arvanitakis (@3nvi)

v0.4.1 (Tue Jun 09 2020)

🐛 Bug Fix

Authors: 1


v0.4.0 (Tue Jun 09 2020)

🚀 Enhancement

Authors: 2


v0.3.1 (Sun Apr 05 2020)

🐛 Bug Fix

  • fix: disable eslint rule no-prototype-builtins #12 (@ardeois)

Authors: 1


v0.3.0 (Sun Apr 05 2020)

🚀 Enhancement

Authors: 1


v0.2.1 (Fri Apr 03 2020)

🐛 Bug Fix

Authors: 1


v0.2.0 (Fri Apr 03 2020)

🚀 Enhancement

Authors: 1


v0.1.4 (Fri Apr 03 2020)

🐛 Bug Fix

Authors: 1


v0.1.3 (Tue Nov 26 2019)

🐛 Bug Fix

Authors: 1


v0.1.2 (Thu Nov 14 2019)

🐛 Bug Fix

Authors: 1


v0.1.1 (Tue Oct 29 2019)

🐛 Bug Fix

  • fix: move graphql to peer dependencies #4 (@ardeois)

Authors: 1


v0.1.0 (Tue Oct 29 2019)

🚀 Enhancement

Authors: 1


v0.0.5 (Tue Oct 29 2019)


v0.0.4 (Tue Oct 29 2019)


v0.0.3 (Tue Oct 29 2019)

🐛 Bug Fix

⚠️ Pushed to master

Authors: 2