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

apollo-mock-schema

v0.1.1

Published

> This project was bootstrapped with [TSDX](https://github.com/jaredpalmer/tsdx).

Downloads

3

Readme

This project was bootstrapped with TSDX.

Apollo Mock Schema

This package is 100% inspired by @stubailo post A new approach to mocking GraphQL data

Motivation

Apollo provides out of the box a MockedProvider component where you can individually mock any graphql operation.

This approach works extremely fine ✅ but it comes with a cost of boilerplate and as your project grows it can get out of hand the number of mocked queries/mutations etc.

This package takes a different approach, as mentioned in Sashko's blog post:

  • Mock your GraphqlQL data for your whole schema.
  • Customize our mocks on a per-component basis.
  • Mock loading and error state with just one line of code.

I have personally been using this approach in quite a large GraphQL project and it definitely helps to keep track of all your mocks in one place, not mentioning the amount of boilerplate that can be reduced by doing so.

Installation

This package depends on the following peer dependencies:

  • @apollo/react-common
  • @apollo/react-components
  • apollo-cache-inmemory
  • apollo-client
  • graphql
  • react

Make sure to have those installed in your project. Then:

yarn add apollo-mock-schema

Api

ApolloMockSchemaProvider

That's the main component which will mainly wrap your application and mock operations

Examples using @testing-library/react

import { ApolloMockSchemaProvider } from 'apollo-mock-schema';
import { render } from '@testing-library/react';
import { Resolvers } from '../generated-resolvers.ts';

const firstName = 'Lorem';
const lastName = 'Ipsum';

const resolvers: Resolvers = () => ({
  Query: {
    user: () => ({
      isAuthenticated: true,
      firstName,
      lastName,
    }),
  },
});

const { queryByText } = render(
  <ApolloMockSchemaProvider<typeof resolvers>
    introspection={require('./schema.json').data}
    resolvers={resolvers}
    overwrite={{
      Query: {
        user: () => ({
          isAuthenticated: false,
        }),
      },
    }}
  >
    <App />
  </ApolloMockSchemaProvider>
);

expect(queryByText(firstName)).toBeInTheDocument();
expect(queryByText(lastName)).toBeInTheDocument();
expect(queryByText('authenticated')).toBeInTheDocument();

Props

| Prop | type | Required | Description | | ------------------- | --------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | resolvers | T extends (...args: any) => any | ✅ | A factory to retrieve your resolvers shape. That really depends on your app's schema and essentially it's going to be forward to addResolveFunctionsToSchema | | children | React.ReactNode / React.ReactElement<any> | ✅ | The application/component to be tested | | introspection | Object | ✅ | Introspection json of your app schema. Generally, this is an auto-generated file by tools like apollo-tooling or graphql-code-generator | | overwrite | DeepPartial<ReturnType<typeof resolvers>> | ⛔️ | Same interface as the output of your resolvers. This is the input for overwriting any GraphQL data. | | graphqlErrors | { message: string }[] | ⛔️ | A list of GraphQL error messages case you intentionally expect an error. | | createApolloCache | () => ApolloCache<any> | ⛔️ | A factory that should return an apollo-cache. Defaults to a simple apollo-inmemory-cache | | error | boolean | ⛔️ | Enable all GraphQL operations to fail. | | loading | boolean | ⛔️ | Enable all GraphQL operations to respond with loading |

Testing a loading state

import { ApolloMockSchemaProvider } from 'apollo-mock-schema';
import { render } from '@testing-library/react';
import { Resolvers } from '../generated-resolvers.ts';
import { resolvers } from '../mocked-resolvers.ts';

const { queryByText } = render(
  <ApolloMockSchemaProvider<typeof resolvers>
    introspection={require('./schema.json').data}
    resolvers={resolvers}
    loading
  >
    <App />
  </ApolloMockSchemaProvider>
);

expect(queryByText(/Loading user.../)).toBeInTheDocument();

Testing an error state

import { ApolloMockSchemaProvider } from 'apollo-mock-schema';
import { render } from '@testing-library/react';
import { Resolvers } from '../generated-resolvers.ts';
import { resolvers } from '../mocked-resolvers.ts';

const { queryByText } = render(
  <ApolloMockSchemaProvider<typeof resolvers>
    introspection={require('./schema.json').data}
    resolvers={resolvers}
    error
  >
    <App />
  </ApolloMockSchemaProvider>
);

expect(queryByText(/GraphQL error while loading user/)).toBeInTheDocument();

createSchemaClient

Internally used on ApolloMockSchema. That's the factory that will return an apollo client with a custom Schema Link

import { createSchemaClient } from 'apollo-mock-schema';

const client = createSchemaClient({
  introspection,
  cache,
  overwrite,
  resolvers,
});

| Parameter | type | Required | Description | | --------------- | ------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | resolvers | T extends (...args: any) => any | true | A factory to retrieve your resolvers shape. That really depends on your app's schema and essentially it's going to be forward to https://www.apollographql.com/docs/graphql-tools/resolvers/#addresolvefunctionstoschema-schema-resolvers-resolvervalidationoptions-inheritresolversfrominterfaces- | | introspection | Object | true | Introspection json of your app schema. Generally this is an auto generated file by tools like apollo-tooling or graphql-code-generator | | overwrite | DeepPartial<ReturnType<typeof resolvers>> | false | Same interface as the output of your resolvers. This is input for overwriting data. | | cache | ApolloCache<any> | false | An apollo-cache instance |

createSchemaErrorLink

Internally used on ApolloMockSchema. That's the factory that will return an apollo client that will fail with an error for all graphql operations.

import { createSchemaErrorLink } from 'apollo-mock-schema';
import { ApolloLink } from 'apollo-link';
import ApolloClient from 'apollo-client';

const link = createSchemaErrorLink({ graphQLErrors });
const client = new ApolloClient({
  link: ApolloLink.from([link]),
  cache,
  defaultOptions: {
    query: {
      errorPolicy: 'all',
      fetchPolicy: 'no-cache',
    },
  },
});

| Parameter | type | Required | Description | | --------------- | ----------------------- | -------- | ------------------------------------------------------------------------ | | graphqlErrors | { message: string }[] | false | A list of GraphQL error messages case you intentionally expect an error. |

Local Development

Below is a list of commands you will probably find useful.

npm start or yarn start

Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for your convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.

Your library will be rebuilt if you make edits.

npm run build or yarn build

Bundles the package to the dist folder. The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).

npm test or yarn test

Runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit.