npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@graphitation/graphql-js-operation-payload-generator

v0.12.10

Published

Generates a payload for a given GraphQL operation expressed in graphql-js AST and a GraphQL Schema.

Downloads

2,921

Readme

@graphitation/graphql-js-operation-payload-generator

The @graphitation/graphql-js-operation-payload-generator package allows you to generate mock payloads for GraphQL operations using the graphql-js AST and a GraphQL schema. It provides similar functionality to Relay's MockPayloadGenerator and is designed for behavior-driven testing of GraphQL components.

🤝 This package works hand-in-hand with @graphitation/apollo-mock-client, to provide a complete testing experience.

📝 Be sure to read the testing guide for a complete picture.

Installation

Install the package using npm:

npm install @graphitation/graphql-js-operation-payload-generator

or using yarn:

yarn add @graphitation/graphql-js-operation-payload-generator

Usage

To generate a mock payload, follow these steps:

  1. Import the necessary dependencies:
import * as MockPayloadGenerator from "@graphitation/graphql-js-operation-payload-generator";
import { buildSchema } from "graphql";
  1. Get a GraphQLSchema object instance of your schema:
const schema = buildSchema(`
  type Query {
    # ...
  }
`);
  1. Define your operation descriptor:
const operation = {
  schema,
  request: {
    node: /* your GraphQL operation */,
    variables: /* your GraphQL operation variables */,
  },
};

The operation descriptor consists of the GraphQL schema and the request descriptor, which includes the GraphQL operation and variables.

  1. Generate the mock payload using the generate function:
const payload = MockPayloadGenerator.generate(operation, mockResolvers);

The generate function takes in the operation descriptor and optional mock resolvers to generate the mock payload for the specified operation.

Mock Resolvers

Mock resolvers are functions that provide mock data for different GraphQL types. By default, the generator will create mock data for all fields in the request. You can define custom mock resolvers for specific types to selectively provide explicit field values for those fields that matter to your test or storybook story.

Here's an example of defining custom mock resolvers:

const mockResolvers = {
  User: (context, generateId) => ({
    id: generateId(),
    name: "John Doe",
    profile_picture: {
      uri: "<mock-value-for-field-'uri'>",
      width: 42,
      height: 42,
    },
  }),
};

In the above example, we define a custom mock resolver for the User type. The resolver function receives a context object and a generateId function and returns the mock data for the User type. Only the id, name, and profile_picture fields are explicitly provided with values, and the rest of the fields will be generated by the default mock resolver.

Example

Here's an example that demonstrates the usage of this package:

import * as MockPayloadGenerator from "@graphitation/graphql-js-operation-payload-generator";
import { graphql } from "@graphitation/graphql-js-tag";
import { buildSchema } from "graphql";

const schema = buildSchema(`
  type Query {
    user(id: ID!): User
  }

  type User {
    id: ID!
    name: String!
    profile_picture: Image
  }

  type Image {
    uri: String!
    width: Int!
    height: Int!
  }
`);

const operation = {
  schema,
  request: {
    node: graphql`
      query SomeQuery($userId: ID!) {
        user(id: $userId) {
          id
          name
          profile_picture {
            uri
            width
            height
          }
        }
      }
    `,
    variables: { userId: "my-id" },
  },
};

Generate mock payload with default values:

const payload = MockPayloadGenerator.generate(operation);
console.log(JSON.stringify(payload, null, 2));

Output:

{
  "data": {
    "__typename": "Query",
    "user": {
      "__typename": "User",
      "id": "<mock-id-2>",
      "name": "<mock-value-for-field-'name'>",
      "profile_picture": {
        "__typename": "Image",
        "uri": "<mock-value-for-field-'uri'>",
        "width": 42,
        "height": 42
      }
    }
  }
}

Generate mock payload with explicit user name:

const mockResolvers = {
  User: (context, generateId) => ({
    id: generateId(),
    name: "John Doe",
    profile_picture: {
      uri: "<mock-value-for-field-'uri'>",
      width: 42,
      height: 42,
    },
  }),
};

const payload = MockPayloadGenerator.generate(
  operation,
  mockResolvers
);

Output:

 {
   "data": {
     "__typename": "Query",
     "user": {
       "__typename": "User",
       "id": "<mock-id-2>",
-      "name": "<mock-value-for-field-'name'>",
+      "name": "John Doe",
       "profile_picture": {
         "__typename": "Image",
         "uri": "<mock-value-for-field-'uri'>",
         "width": 42,
         "height": 42
       }
     }
   }
 }

Schema Type-Checking and Auto-Completion

If you want type-checking and auto-completion support for the mock resolvers, you can provide a type map using the generate function. The type map consists of type names as keys and the corresponding GraphQL types as values.

For example, if you are using @graphql-code-generator, you can emit the type map using the @graphitation/graphql-codegen-typescript-typemap-plugin plugin. This plugin generates TypeScript type definitions based on your GraphQL schema and can include the type map.

Here's an example configuration in codegen.yml:

Copy code
schema: http://localhost:3000/graphql
generates:
  ./src/types.ts:
    plugins:
      - typescript
      - @graphitation/graphql-codegen-typescript-typemap-plugin
    config:
      allowEnumStringTypes: true

By providing the type map, you can benefit from improved type safety and editor support when working with the generated mock payloads.

That's it! You can now generate mock payloads for your GraphQL operations using @graphitation/graphql-js-operation-payload-generator. Use these mock payloads in your tests to ensure your GraphQL components behave as expected in different scenarios.