Skip to content
This repository was archived by the owner on Dec 6, 2024. It is now read-only.

batrdn/nock-graphql

Repository files navigation

nock-graphql

A nock-based GraphQL testing library that provides a functionality to mock queries and mutations. In contrast to Apollo's MockedProvider, nock allows a realistic testing with the actual http calls being made from your client code.

Installing

You'll need nock, cross-fetch as peer dependencies in order to use this library.

npm install -D nock-graphql nock cross-fetch

Additionally, you need to set up global fetch implementation incorporated in your jest environment:

global.fetch = require('cross-fetch')

or, directly in your ApolloClient

const client = new ApolloClient({
  link: new HttpLink({ fetch, uri: ENDPOINT }),
});

Usage

I. Create nock-graphql instance

A. You could create it globally:

// Create the instance in a separate file and export it.
import { NockGraphQL } from 'nock-graphql';

export const nockgql = new NockGraphQL('http://localhost:4000/graphql');

B. Create directly in the test files:

import { NockGraphQL } from 'nock-graphql';

let nockgql: NockGraphQL;

beforeAll(() => {
  nockgql = new NockGraphQL('http://localhost:4000/graphql');
});

II. Mocking queries

import { gql } from 'graphql-tag';
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import { MockConfig } from 'nock-graphql';

type QueryVariables = {
  id: string;
};

type QueryResult = {
  foo: { bar: string };
};

const GetQuery = gql`
  query Test($id: String) {
    foo(id: $id) {
      bar
    }
  }
`;

beforeEach(() => {
  client = new ApolloClient({
    link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
    cache: new InMemoryCache({ addTypename: false }),
  });
});

afterEach(() => {
  nockgql.cleanup();
});

test('should match  the query', async () => {
  const config: MockConfig<QueryVariables, QueryResult> = {
    document: GetQuery,
    variables: { id: '1' },
    data: {
      foo: {
        bar: 'Hello, World',
      },
    },
  };

  const scope = nockgql.mock(config);
  await client.query({ query: GetQuery, variables: { id: '1' } });

  scope.done();
});

About

Minimal client-side GraphQL testing tool

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy