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

graphql-automock

v0.5.0

Published

Automock GraphQL schemas for better testing

Downloads

45

Readme

⭐️ graphql-automock ⭐️

Automatically mock GraphQL schemas for better testing.

Features:

  • Automatically and deterministically mock GraphQL schemas
  • Mock react-apollo for simple UI testing
  • Control schema execution to reliably test loading and success states

Getting started

Install via npm or yarn:

npm install --save-dev graphql-automock
yarn add --dev graphql-automock

Mocking just the schema

Simply pass your GraphQL type definitions to mockSchema and you're ready to go:

import { mockSchema } from "graphql-automock";
import { graphql } from "graphql";

const types = `
  type Query {
    recentPosts: [Post!]!
  }

  type Post {
    id: ID!
    content: String!
    likes: Int!
  }
`;

const mocked = mockSchema(types);

const query = `{
  recentPosts {
    id
    content
    likes
  }
}`;

graphql(mocked, query);

Without any further configuration, this query will return:

{
  "data": {
    "recentPosts": [
      {
        "id": "recentPosts.0.id",
        "content": "recentPosts.0.content",
        "likes": 2
      },
      {
        "id": "recentPosts.1.id",
        "content": "recentPosts.1.content",
        "likes": 2
      }
    ]
  }
}

To understand how these values are derived, see Default values.

Mocking react-apollo

In addition to schema mocking, <MockApolloProvider> makes the testing of your UI components much easier.

Wrapping components in a <MockApolloProvider> allows any graphql() and <Query> components in the tree to receive mock data. However note that components will first enter a loading state before the query resolves and components re-render. <MockApolloProvider>, together with a controller, allows you to step through GraphQL execution to test both loading and ready states.

import { MockApolloProvider, controller } from "graphql-automock";
import TestUtils from "react-dom/test-utils";

it("renders a Post", async () => {
  const tree = TestUtils.renderIntoDocument(
    <MockApolloProvider schema={types}>
      <Post id="123" />
    </MockApolloProvider>
  );

  // Execution is automatically paused, allowing you to test loading state
  const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);
  expect(spinners).toHaveLength(1);

  // Allow schema to run, and wait for it to finish
  await controller.run();

  // Test success state
  const content = TestUtils.scryRenderedComponentsWithType(tree, Content);
  expect(content).toHaveLength(1);
});

Customizing mocks

Automatically mocking the entire schema with sensible, deterministic data allows test code to customize only the data that affects the test. This results in test code that is more concise and easier to understand:

// We're only interested in the behaviour of likes...
it("hides the likes count when there are no likes", () => {
  const mocks = {
    Post: () => ({
      likes: 0 // ...so we only customize that data
    })
  };

  // Using mockSchema
  const mockedSchema = mockSchema({
    schema: types,
    mocks: mocks
  });

  // Using MockApolloProvider
  const mockedElements = (
    <MockApolloProvider schema={types} mocks={mocks}>
      <Post id="123" />
    </MockApolloProvider>
  );

  // Continue with test...
});

Mocking errors

Both GraphQL errors and network errors can be mocked.

Mocking GraphQL errors

Just like with a real GraphQL implementation, GraphQL errors are generated by throwing an error from a (mock) resolver.

import { mockSchema } from "graphql-automock";

mockSchema({
  schema: types,
  mocks: {
    Post: () => {
      throw new Error("Could not retrieve Post");
    }
  }
});

Mocking network errors

Since network errors are external to the GraphQL schema, they are simulated through the controller.

import { MockApolloProvider, controller } from "graphql-automock";
import TestUtils from "react-dom/test-utils";

it("renders a Post", async () => {
  const tree = TestUtils.renderIntoDocument(
    <MockApolloProvider schema={types}>
      <Post id="123" />
    </MockApolloProvider>
  );

  // Test loading state
  const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);
  expect(spinners).toHaveLength(1);

  // Simulate a network error
  await controller.run({
    networkError: () => new Error("Disconnected")
  });

  // Test error state
  const errorMessage = TestUtils.scryRenderedComponentsWithType(
    tree,
    ErrorMessage
  );
  expect(errorMessage).toHaveLength(1);
});

Default values

To ensure that tests are reliable, the values generated by graphql-automock are 100% deterministic. The following default values are used:

  • Boolean: true
  • Int: 2
  • Float: 3.14
  • String: Path to value
  • ID: Path to value
  • Enum: The first enum value, sorted alphabetically by name
  • Interface: The first possible implementation, sorted alphabetically by name
  • Union: The first possible member type, sorted alphabetically by name
  • List length: 2

API Reference

mockSchema()

Create a mocked GraphQL schema.

function mockSchema(schema: String | GraphQLSchema): GraphQLSchema;

function mockSchema({
  schema: String | GraphQLSchema,
  mocks: { [String]: MockResolverFn }
}): GraphQLSchema;

mockApolloClient()

Create a mocked Apollo Client.

function mockApolloClient(schema: String | GraphQLSchema): ApolloClient;

function mockApolloClient({
  schema: String | GraphQLSchema,
  mocks: { [String]: MockResolverFn },
  controller: Controller
}): ApolloClient;

<MockApolloProvider>

React component that renders a mocked ApolloProvider.

<MockApolloProvider
  schema={String | GraphQLSchema}
  mocks={{ [String]: MockResolverFn }}
  controller={Controller}
>

type MockResolverFn

type MockResolverFn = (parent, args, context, info) => any;

controller

Gives precise control over GraphQL execution, as well as enabling network errors to be simulated.

pause()

function pause(): void;

Pause GraphQL execution until it is explicitly resumed.

Controller starts in this state.

run()

function run(): Promise<void>;
function run({ networkError: () => any }): Promise<void>;

Resume GraphQL execution if it is paused.

Returns a Promise that resolves when all pending queries have finished executing. If execution was not paused, then it returns a resolved Promise.

If a networkError function is provided, pending and subsequent queries will fail with the result of calling that function. The function is called once for each query.