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

@iam4x/cypress-graphql-mock

v0.0.1

Published

Mock out a GraphQL schema from the client

Downloads

348

Readme

cypress-graphql-mock

Adds commands for executing a mocked GraphQL server using only the client

Installation

npm install cypress-graphql-mock

in Cypress' commands.js add:

import { setBaseGraphqlMocks } from "cypress-graphql-mock";

// Set all of your base mocks, as described in
// https://www.apollographql.com/docs/graphql-tools/mocking/#default-mock-example
setBaseGraphqlMocks({
  User: () => ({
    id: () => randomId(),
    name: "Test User"
  }),
  DateTime(obj, args, context, field) {
    if (obj[field.fieldName]) return obj[field.fieldName];
    return new Date("2019-01-01");
  }
});

See the "code generation" section below for more info on how to generate types for this.

Instructions

Adds .mockGraphql() and .mockGraphqlOps() methods to the cypress chain.

The .mockGraphql should be called in the Cypress before or beforeEach block config to setup the server. This method takes a schema, either in the form of one or more SDL files, or as the JSON result of an introspection query.

const schema = fs.readFileSync("../../app-schema.graphql", "utf8");
// alternatively, using a dumped introspection query:
// const schema = require('../../dumped-schema.json')

beforeEach(() => {
  cy.server();
  cy.mockGraphql({ schema });
});

Actually it is not possible to use fs.readFileSync right in the cypress tests. So here you can create custom command. Add this to your cypress/plugins/index.js.

module.exports = (on, config) => {
  on("task", {
    getSchema() {
      return fs.readFileSync(
        path.resolve(__dirname, "../../app-schema.graphql""),
        "utf8"
      );
    }
  });
};

And then in the code you will be able to

beforeEach(() => {
  cy.task("getSchema").then(schema => {
    cy.mockGraphql({
      schema,
      operations: { ... }
    });
  });
});

By default, it will use the /graphql endpoint, but this can be changed depending on the expected server implementation.

beforeEach(() => {
  cy.server();
  cy.mockGraphql({
    schema,
    endpoint: "/gql"
  });
});

It takes an "operations" object, representing the named operations of the GraphQL server. This is combined with the "mocks" option, to modify the output behavior per test.

The .mockGraphqlOps() allows you to configure the mock responses at a more granular level

For example, if we has a query called "UserQuery" and wanted to explicitly force a state where a viewer is null (logged out), it would look something like:

.mockGraphqlOps({
  operations: {
    UserQuery: {
      viewer: null
    }
  }
})

Examples

Real application example

Simple mutation

Just return mutation result. Make sure that mostly always you will need to duplicate mutation name 1st time as operation key, and 2nd as return data object key.

cy.server();
cy.mockGraphql({ schema });
cy.mockGraphqlOps({
  operations: {
    userNameChange: {
      userNameChange: {
        name: "New user name"
      }
    }
  }
});

It is also possible to pass a function to simulate dynamic resolver.

cy.server();
cy.mockGraphql({ schema });
cy.mockGraphqlOps({
  operations: {
    userNameChange: variables => ({
      userNameChange: {
        viewer: {
          name: variables.name
        }
      }
    })
  }
});

Delay

In order to test asynchronous behavior sometimes you will need to delay your graphql request. This can be done with a help of delay option.

cy.mockGraphqlOps({
  operations: {
    delay: 1000, // 1 second
    userNameChange: new GraphQLError("Your message goes here")
  }
});

Code Generation

This plugin ships with a graphql-code-generator plugin to generate typings for the "RootTypes" and the mock operations.

See the graphql-code-generator docs around plugins, and the example app / codegen.yml in the root for an example use:

test/cypress/generated/generated-mock-types.d.ts:
  documents: "test/test-graphql-app/**/*.jsx"
  plugins:
    - typescript
    - typescript-operations
    - cypress-graphql-mock/codegen
  config:
    enumsAsTypes: true

Error handling

import { GraphQLError } from "graphql";

cy.mockGraphqlOps({
  delay: 1000, // wait 1 second
  operations: {
    userNameChange: new GraphQLError("Your message goes here")
  }
});

It is also possible to throw error from the function. Just return or throw a GraphQLError.

cy.mockGraphqlOps({
  operations: {
    userNameChange: variables => {
      if (!variables.name) {
        throw new GraphQLError("Name is required");
      }
    }
  }
});

License

MIT