• Stars
    star
    134
  • Rank 270,967 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Test helper for writing apollo-server integration tests

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();
await apolloServer.start();
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.

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.

More Repositories

1

django-drip

πŸ’§ Use Django admin to manage drip campaign emails using querysets on Django's User model.
Python
636
star
2

django-rest-hooks

πŸ’Œ Add webhook subscriptions to your Django app.
Python
559
star
3

resthooks

A lightweight subscription notification layer on top of your existing REST API
HTML
551
star
4

django-knowledge

Add a help desk or knowledge base to your Django project with only a few lines of boilerplate code.
Python
490
star
5

email-reply-parser

πŸ“§ Email reply parser library for Python
Python
462
star
6

zapier-platform

The SDK for you to build an integration on Zapier
JavaScript
344
star
7

zapier-platform-cli

πŸ’» Build Zapier integrations and test locally using the JavaScript tools you already know.
JavaScript
259
star
8

kubechecks

Check your Kubernetes changes before they hit the cluster
Go
162
star
9

Zapier-for-Alfred

An Alfred workflow to trigger Zaps
122
star
10

stripeboard

A simple Django app that collects and displays Stripe data.
JavaScript
119
star
11

prom-aggregation-gateway

An aggregating push gateway for Prometheus
Go
116
star
12

google-yolo-inline

A demo of how to include Google One-tap sign up anywhere on your own site
HTML
90
star
13

node-resthooksdemo

A simple node.js RESTHooks demo built upon the Sails Web Framework
JavaScript
68
star
14

intl-dateformat

Format a date using Intl.DateTimeFormat goodness.
TypeScript
62
star
15

redux-router-kit

Routing tools for React+Redux
JavaScript
51
star
16

visual-builder

Learn how to use Zapier Visual Builder to create new Zapier integrations
HTML
51
star
17

django-rest-framework-jsonmask

Exposes Google Partial Response syntax in Django REST Framework
Python
46
star
18

react-element-portal

Blend React into your exising site by rendering elements inline, targeting an element by id.
JavaScript
34
star
19

zapier-platform-example-app-github

An example GitHub app for the Zapier platform.
JavaScript
27
star
20

tfbuddy

Terraform Cloud pull request alternate workflow
Go
26
star
21

preoomkiller-controller

Preoomkiller Controller evicts pods gracefully before they get OOMKilled by Kubernetes
Go
24
star
22

zapier-platform-core

πŸ”Œ The core Zapier platform library / SDK.
JavaScript
24
star
23

conspiracysanta.com

No longer maintained: A better secret santa for teams.
JavaScript
19
star
24

django-stalefields

No longer updated: Automatic .update() instead of .save() for models.
Python
19
star
25

litdoc

πŸ“ A simple Markdown-based 3-column documentation builder.
HTML
18
star
26

django-birdcage

Utilities for maintaining forwards compatibility with Django releases.
Python
15
star
27

zapier-platform-schema

πŸ“– The core Zapier Platform schema.
JavaScript
15
star
28

jsonmask

Implements Google Partial Response dictionary pruning in Python
Python
14
star
29

resthookdemo

A quick and easy demo application for rest hooks.
CSS
13
star
30

profiling-python-like-a-boss

Sample code for a Zapier engineering blog post
Python
13
star
31

zapier-platform-example-app-onedrive

An example Zapier Platform App that demonstrates a complete App using the OneDrive API
JavaScript
12
star
32

zapier-platform-example-app-rest-hooks

An example Zapier Platform App that demonstrates REST Hook Triggers
JavaScript
10
star
33

saasr

A SaaS subscription simulator - a tool to learn about the statistical mechanics of subscriptions
R
10
star
34

langchain-nla-util

Python
7
star
35

awsjavasdk

Boilerplate rJava Access to the AWS Java SDK
R
6
star
36

zapier-sugarcrm-box

No longer updated: A vagrant box to boot up an instance of sugarcrm for local testing
PHP
6
star
37

docker-brubeck

A simple Dockerfile for GitHub's Brubeck (StatsD-compatible metrics aggregator).
Shell
5
star
38

type-system-benchmarks

Benchmark several type systems and ways to build them (right now Typescript and Flow)
TypeScript
4
star
39

zapier-platform-example-app-files

An example Zapier Platform App that demonstrates file handling (stashFile and dehydrate).
JavaScript
4
star
40

redis-statsd

A simple script which pipes Redis statistics into StatsD
Python
4
star
41

zapier-platform-example-app-session-auth

An example Zapier Platform App that demonstrates session authentication (username/password exchange for session key)
JavaScript
4
star
42

eslint-plugin-zapier

🚿 A shareable version of the .eslintrc file used internally at Zapier.
JavaScript
4
star
43

zapier-platform-example-app-minimal

Zapier CLI Platform Minimal App
JavaScript
4
star
44

zapier-platform-example-app-custom-auth

An example Zapier Platform App that demonstrates custom authentication (API keys)
JavaScript
4
star
45

zapier-platform-example-app-oauth2

An example Zapier Platform App that demonstrates OAuth2
JavaScript
4
star
46

zapier-platform-example-app-trigger

An example Zapier Platform App that demonstrates Triggers
JavaScript
3
star
47

kairos

Python
3
star
48

zapier-platform-example-app-dynamic-dropdown

An example Zapier Platform App that demonstrates Dynamic Dropdowns
JavaScript
3
star
49

zapier-zapier-zapier-zapier-coffee-script

No longer updated: Zapier's very own CoffeeScript version which tweaks for our internal tools.
CoffeeScript
3
star
50

docker-proxysql

ProxySQL Docker images
Shell
2
star
51

zapier-platform-example-app-resource

An example Zapier Platform App that demonstrates Resources
JavaScript
2
star
52

nano-flux

No longer maintained: Tiny, simple flux lib.
JavaScript
2
star
53

zapier-platform-example-app-create

An example Zapier Platform App that demonstrates Creates
JavaScript
2
star
54

is-it-online

Wait for a URL to return 2XX, then show an OS notification and exit.
JavaScript
2
star
55

zapier-platform-example-app-microsoft-exchange

An example Zapier CLI app for MS Exchange
JavaScript
2
star
56

django-linttest

Lint Test is a simple Django app to perform flake8 linting on your project
Python
2
star
57

release-notes

an npm module for pulling merged PRs and generating release notes from them
TypeScript
2
star
58

babel-preset-zapier

🏯 A babel preset for Zapier
JavaScript
1
star
59

parquetr

Read/Write Parquet from R
R
1
star
60

docker-statsd

Run StatsD in a Docker container.
JavaScript
1
star
61

proxysql-benchmark

Benchmark proxysql
Python
1
star
62

docker-graphite

A simple Dockerfile that runs Graphite/Carbon (and nothing else!)
Shell
1
star
63

sentinel-graylog

A simple script which pipes Redis Sentinel messages into Graylog
Python
1
star
64

ecr-catalog-refresh

Simple sidecar to refresh a catalogfile from ECR
Python
1
star
65

zapier-platform-example-app-basic-auth

An example Zapier Platform App that demonstrates Basic Auth
JavaScript
1
star
66

diff-match-patch-cython

A quick hack that speeds up dmp by about ~3x.
Python
1
star
67

terraform-provider-opslevel

Terraform provider for OpsLevel.com
Go
1
star
68

zapier-platform-example-app-search

An example Zapier Platform App that demonstrates Searches
JavaScript
1
star