Skip to content

Instantly share code, notes, and snippets.

View JakeDawkins's full-sized avatar

Jake Dawkins JakeDawkins

View GitHub Profile
@JakeDawkins
JakeDawkins / test.js
Created May 1, 2018 01:56
Example of integration testing a GraphQL schema
import { schema } from '../my-schema';
// Docs for `graphql` function
// http://graphql.org/graphql-js/graphql/#graphql
import { graphql } from 'graphql';
it('executes a query that looks up some data', async () => {
// optionally create some fake context (i.e. data connectors)
const myFakeContext = { restConnectionOne: { findOne: jest.fn() } };
const { ApolloServer } = require('apollo-server');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authorization || '';
// try to retrieve a user with the token
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authentication || '';
// try to retrieve a user with the token
const user = getUser(token);
// optionally block the user
// we could also check user roles/permissions here
if (!user) throw new AuthorizationError('you must be logged in');
users: (root, args, context) => {
if (!context.user) return null;
return ['bob', 'jake'];
}
users: (root, args, context) => {
if (!context.user || !context.user.roles.includes('admin')) return null;
return context.models.User.getAll();
}
export const User = {
getAll: () => { /* fetching/transform logic for all users */ },
getById: (id) => { /* fetching/transform logic for a single user */ },
getByGroupId: (id) => { /* fetching/transform logic for a group of users */ },
};
type Query {
user (id: ID!): User
article (id: ID!): Article
}
type Article {
author: User
}
type User {
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authentication || '';
// try to retrieve a user with the token
const user = getUser(token);
// optionally block the user
// we could also check user roles/permissions here
if (!user) throw new AuthenticationError('you must be logged in to query this schema');
export const generateUserModel = ({ user }) => ({
getAll: () => { /* fetching/transform logic for all users */ },
getById: (id) => { /* fetching/transform logic for a single user */ },
getByGroupId: (id) => { /* fetching/transform logic for a group of users */ },
});
getAll: () => {
if(!user || !user.roles.includes('admin')) return null;
return fetch('http://myurl.com/users');
}