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

@zhouzi/apollo-server-integration-testing

v2.3.1

Published

Test helper for writing apollo-server integration tests

Downloads

2

Readme

apollo-server-integration-testing

This package exports an utility function for writing apollo-server integration tests:

import { createTestClient } from 'apollo-server-integration-testing';

Usage

This function takes in an apollo server instance and returns a function that you can use to run operations against your schema, and assert on the results.

Example usage:

import { createTestClient } from 'apollo-server-integration-testing';
import { createApolloServer } from './myServerCreationCode';

const apolloServer = await createApolloServer();
const { query, mutate } = createTestClient({
  apolloServer,
});

const result = await query(`{ currentUser { id } }`);

expect(result).toEqual({
  data: {
    currentUser: {
      id: '1',
    },
  },
});

const UPDATE_USER = `
  mutation UpdateUser($id: ID!, $email: String!) {
    updateUser(id: $id, email: $email) {
      user {
        email
      }
    }
  }
`;

const mutationResult = await mutate(UPDATE_USER, {
  variables: { id: 1, email: '[email protected]' },
});

expect(mutationResult).toEqual({
  data: {
    updateUser: {
      email: '[email protected]',
    },
  },
});

This allows you to test all the logic of your apollo server, including any logic inside of the context option that you can pass to the ApolloServer constructor.

Mocking the Request or Response object

createTestClient automatically mocks the Request and Response objects that will be passed to the context option of your ApolloServer constructor, so testing works out of the box. You can also extend the mocked Request or Response object with additional keys by passing an extendMockRequest or extendMockResponse field to createTestClient:

const { query } = createTestClient({
  apolloServer,
  extendMockRequest: {
    headers: {
      cookie: 'csrf=blablabla',
      referer: '',
    },
  },
  extendMockResponse: {
    locals: {
      user: {
        isAuthenticated: false,
      },
    },
  },
});

This is useful when your apollo server context option is a callback that operates on the passed in req key, and you want to inject data into that req object.

As mentioned above, if you don't pass an extendMockRequest to createTestClient, we provide a default request mock object for you. See https://github.com/howardabrams/node-mocks-http#createrequest for all the default values that are included in that mock.

setOptions

You can also set the request and response mocking options after the creation of the test client, which is a cleaner and faster way due not needing to create a new instance for any change you might want to do the request or response.

const { query, setOptions } = createTestClient({
  apolloServer,
});

setOptions({
  // If "request" or "response" is not specified, it's not modified
  request: {
    headers: {
      cookie: 'csrf=blablabla',
      referer: '',
    },
  },
  response: {
    locals: {
      user: {
        isAuthenticated: false,
      },
    },
  },
});

Why not use apollo-server-testing?

You can't really write real integration tests with apollo-server-testing, because it doesn't support servers which rely on the context option being a function that uses the req object (see this issue for more information).

Real apollo-servers support this behavior, but the test client created with apollo-server-testing does not. For example:

import { createTestClient } from 'apollo-server-testing';

it('will not work', () => {
 const { query } = createTestClient(
   new ApolloServer({
     schema,
     context: ({ req }) => {
       return doSomethingWithReq(req); // this won't work because `req` is `undefined`.
     }
   })
 );

 // Any middleware or resolver code that depends on `context` will not work when this runs, because
 // the `context` function does *not* get passed `req` as expected.
 const result = await query(
   `{ currentUser { id } }`
 )
});

The official integration example code from Apollo solves this by instantiating an ApolloServer inside the test and mocking the context value by hand. But I don't consider this a real integration test, since you're not using the same instantiation code that your production code uses.

Development

If you want to help out, here's a TODO list:

  • [x] Strip flow types before publishing (or switch to Typescript?)
  • [x] Compile to non-es6 module syntax
  • [x] Add tests
  • [x] Add auto-formatting

Support

This package should work for consumers using apollo-server-express. We don't plan on supporting any other node server integrations at this time.