Unleashing GraphQL Type-Based Mocking

skathuria29

Saloni Kathuria

Posted on October 12, 2023

Unleashing GraphQL Type-Based Mocking

Developing GraphQL APIs often involves creating and testing the API’s functionality, and one essential aspect of this process is generating mock data. Mock data helps developers build and test GraphQL queries and mutations without relying on a real database or production data. In this article, we’ll explore how to use graphql-codegen-typescript-mock-data to easily generate mock data based on your GraphQL schema.

Understanding GraphQL Schemas

A GraphQL schema defines the types and operations available in your API. It includes information about queries, mutations, and the data types that can be retrieved or manipulated. The schema acts as a contract between the client and server, ensuring that clients request only valid data.

Generating Mock Data with graphql-codegen-typescript-mock-data

The graphql-codegen-typescript-mock-data is a powerful tool that works in conjunction with graphql-codegen. It generates TypeScript types and mock data for your GraphQL schema, making it easier to develop and test your API.

Steps to get started with graphql-codegen-typescript-mock-data:

- Install Dependencies

npm install - save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-mock-data graphql

Enter fullscreen mode Exit fullscreen mode

- Creating a GraphQL Schema

To get started, you need a GraphQL schema for your API. You can define your schema using the GraphQL Schema Definition Language (SDL) or a programmatic approach, depending on your preferences. Here’s a simple example of an SDL-based schema:

type Post {
  id: ID!
  title: String!
  content: String!
}

type Query {
  getPosts: [Post!]!
}
Enter fullscreen mode Exit fullscreen mode

With this schema, you can query for a list of posts. Now, let’s see how to use graphql-codegen-typescript-validation-schema to generate TypeScript types and mock data based on this schema.

- Configure Code Generation

schema: ./src/schema.ts
require:
  - ts-node/register/transpile-only
generates:
  src/generated-types.ts:
    plugins:
      - typescript
      - typescript-resolvers
  src/generated-mocks.ts:
    plugins:
      - typescript-mock-data:
          typesFile: './generated-types.ts'   
Enter fullscreen mode Exit fullscreen mode

This configuration specifies the schema path and the output file for the generated TypeScript code. Also generates mock data using typescript-mock-data plugin.

The configuration has the following fields:

schema: specifies the path to the local/ graphql schema endpoint

generates: A map where the key represents an output path for the generated code, and the value represents a set of relevant options for that specific file. Below are the possible options that can be specified.

  • Generating types in output file src/generated-types.ts , using plugins typescript and typescript-resolver .

  • Generating mocks from the types in the putput file src/generated-mocks.ts , using the plugin typescript-mock-data

Once you run this command it will create 2 files one with generated types and other with generated mocks using the types.

The generated mock data file looks like this

export const aPost = (overrides?: Partial<Post>): Post => {
  return {
    id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '0550ff93-dd31-49b4-8c38-ff1cb68bdc38',
    title: overrides && overrides.hasOwnProperty('title') ? overrides.title! : 'aliquid',
    content: overrides && overrides.hasOwnProperty('content') ? overrides.title! : 'rerum', 
  };
};
Enter fullscreen mode Exit fullscreen mode

- Use Mock Data

You can use the generated mock data in your tests, development environment, or anywhere else you need mock data.

Here we will see the usage of it in unit testing:

const { aPost } from 'src/generated-mocks';

const post = aPost({ title: 'Hello World' });

// will create a post object with `title` property overridden to `Hello World`
Enter fullscreen mode Exit fullscreen mode

The mockPost() function will provide you with mock data for a Post type:

{
  "id": "0550ff93-dd31-49b4-8c38-ff1cb68bdc38",
  "title": "Hello World",
  "content": "rerum"
}
Enter fullscreen mode Exit fullscreen mode

Generating mock data for your GraphQL API is crucial for effective development and testing. With tools like graphql-codegen-typescript-mock-data, you can streamline the process by automatically generating TypeScript types and mock data based on your GraphQL schema. This simplifies development, reduces reliance on real data sources, and ensures consistent and reliable testing for your GraphQL API.

Thanks for reading :)

💖 💪 🙅 🚩
skathuria29
Saloni Kathuria

Posted on October 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related