Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test Utils for Apollo-server #1909

Merged
merged 17 commits into from
Nov 5, 2018
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 75 additions & 75 deletions package-lock.json

Large diffs are not rendered by default.

38 changes: 38 additions & 0 deletions packages/apollo-server-core/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ import {
} from './playground';

import { generateSchemaHash } from './utils/schemaHash';
import {
processGraphQLRequest,
GraphQLRequestContext,
GraphQLRequest,
} from './requestPipeline';

import { Headers } from 'apollo-server-env';

const NoIntrospection = (context: ValidationContext) => ({
Field(node: FieldDefinitionNode) {
Expand Down Expand Up @@ -502,4 +509,35 @@ export class ApolloServerBase {
...this.requestOptions,
} as GraphQLOptions;
}

public async executeOperation(
request: GraphQLRequest,
contextArgs: Record<string, any>,
) {
let options;

try {
options = await this.graphQLServerOptions(contextArgs);
} catch (e) {
e.message = `Invalid options provided to ApolloServer: ${e.message}`;
throw new Error(e);
}

if (typeof options.context === 'function') {
options.context = (options.context as () => never)();
}

const requestCtx: GraphQLRequestContext = {
request,
context: options.context || {},
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
cache: options.cache!,
response: {
http: {
headers: new Headers(),
},
},
};

return processGraphQLRequest(options, requestCtx);
}
}
5 changes: 5 additions & 0 deletions packages/apollo-server-testing/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

### vNEXT

* `apollo-server-testing`: Added createTestClient function
7 changes: 7 additions & 0 deletions packages/apollo-server-testing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# apollo-server-testing

[![npm version](https://badge.fury.io/js/apollo-server-testing.svg)](https://badge.fury.io/js/apollo-server-testing)
[![Build Status](https://circleci.com/gh/apollographql/apollo-server.svg?style=svg)](https://circleci.com/gh/apollographql/apollo-server)

This is the testing module of the Apollo community GraphQL Server. [Read the docs.](https://www.apollographql.com/docs/apollo-server/)
[Read the CHANGELOG.](https://github.com/apollographql/apollo-server/blob/master/CHANGELOG.md)
3 changes: 3 additions & 0 deletions packages/apollo-server-testing/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const config = require('../../jest.config.base');

module.exports = Object.assign(Object.create(null), config);
32 changes: 32 additions & 0 deletions packages/apollo-server-testing/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "apollo-server-testing",
abernix marked this conversation as resolved.
Show resolved Hide resolved
"version": "2.2.0-alpha.0",
"description": "Test utils for apollo-server",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-testing"
},
"keywords": [
"GraphQL",
"Apollo",
"Server",
"Javascript"
],
"author": "Jonas Helfer <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/apollographql/apollo-server/issues"
},
"homepage": "https://github.com/apollographql/apollo-server#readme",
"engines": {
"node": ">=6"
},
"dependencies": {
"apollo-server-core": "file:../apollo-server-core"
},
"peerDependencies": {
"graphql": "^0.12.0 || ^0.13.0 || ^14.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const { ApolloServerBase, gql } = require('apollo-server-core');
const createTestClient = require('../createTestClient');

describe('createTestClient', () => {
const typeDefs = gql`
type Query {
test(echo: String): String
# this resolver uses context
hello: String
}

type Mutation {
increment: Int!
}
`;

const resolvers = {
Query: {
test: (_, { echo }) => echo,
hello: (_, __, { person }) => {
return `hello ${person}`;
},
},
Mutation: {
increment: () => 1,
},
};

const myTestServer = new ApolloServerBase({
typeDefs,
context: () => ({ person: 'tom' }),
resolvers,
});

it('allows queries', async () => {
const query = `{ test(echo: "foo") }`;
const client = createTestClient(myTestServer);
const res = await client.query({ query });
expect(res.data).toEqual({ test: 'foo' });
});

it('allows mutations', async () => {
const mutation = `mutation increment { increment }`;
const client = createTestClient(myTestServer);
const res = await client.mutate({ mutation });
expect(res.data).toEqual({ increment: 1 });
});

it('allows variables to be passed', async () => {
const query = `query test($echo: String){ test(echo: $echo) }`;
const client = createTestClient(myTestServer);
const res = await client.query({ query, variables: { echo: 'wow' } });
expect(res.data).toEqual({ test: 'wow' });
});

it('uses default context function if not overwritten', async () => {
const query = `{ hello }`;
const client = createTestClient(myTestServer);
const res = await client.query({ query });
expect(res.data).toEqual({ hello: 'hello tom' });
});

it('allows mocking of context', async () => {
const query = `{ hello }`;
const client = createTestClient(myTestServer, () => ({ person: 'mary' }));
const res = await client.query({ query });
expect(res.data).toEqual({ hello: 'hello mary' });
});

it('allows query documents as input', async () => {
const query = gql`
{
test(echo: "foo")
}
`;
const client = createTestClient(myTestServer);
const clientRes = await client.query({ query });
expect(clientRes.data).toEqual({ test: 'foo' });

const mutation = gql`
mutation increment {
increment
}
`;
const mutationRes = await client.mutate({ mutation });
expect(mutationRes.data).toEqual({ increment: 1 });
});
});
5 changes: 5 additions & 0 deletions packages/apollo-server-testing/src/__tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../../../tsconfig.test.base",
"include": ["**/*"],
"references": []
}
26 changes: 26 additions & 0 deletions packages/apollo-server-testing/src/createTestClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ApolloServerBase, gql } from 'apollo-server-core';
import { print } from 'graphql';

const createTestClient = (server: ApolloServerBase, ctxFn: any) => {
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
// if a context fn is required, overwrite the old one
// allows easy mocking of the context
if (ctxFn) server.context = ctxFn;

const executeOperation = server.executeOperation.bind(server);
return {
query: ({ query, ...rest }) =>
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
executeOperation({
// print the query document if it isn't a string
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
query: typeof query === 'string' ? query : print(query),
...rest,
}),
mutate: ({ mutation, ...rest }) =>
executeOperation({
// print the query document if it isn't a string
query: typeof mutation === 'string' ? mutation : print(mutation),
...rest,
}),
};
};

module.exports = createTestClient;
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 5 additions & 0 deletions packages/apollo-server-testing/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const createTestClient = require('./createTestClient');
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved

module.exports = {
JakeDawkins marked this conversation as resolved.
Show resolved Hide resolved
createTestClient,
};
12 changes: 12 additions & 0 deletions packages/apollo-server-testing/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["src/**/*"],
"exclude": ["**/__tests__", "**/__mocks__"],
"references": [
{ "path": "../apollo-server-core" }
]
}