Created
August 5, 2020 22:34
-
-
Save LeeCheneler/de0ddcbbbe234086b1331822bd5d5c95 to your computer and use it in GitHub Desktop.
apollo server test client with support for context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createTestClient } from "apollo-server-testing"; | |
import { ApolloServer } from "apollo-server"; | |
import { | |
createResolvers, | |
typeDefs, | |
createContext, | |
Context, | |
CreateContextOptions, | |
} from "./server"; | |
import { DocumentNode } from "graphql"; | |
type StringOrAst = string | DocumentNode; | |
interface Query { | |
query: StringOrAst; | |
mutation?: undefined; | |
variables?: { | |
[name: string]: any; | |
}; | |
operationName?: string; | |
context?: Context; | |
} | |
interface Mutation { | |
mutation: StringOrAst; | |
query?: undefined; | |
variables?: { | |
[name: string]: any; | |
}; | |
operationName?: string; | |
context?: Context; | |
} | |
interface CreateApolloTestClientOptions { | |
createContextOptions: CreateContextOptions; | |
} | |
export const createApolloTestClient = ( | |
options: CreateApolloTestClientOptions | |
) => { | |
const defaultContext: Context = { | |
req: { | |
headers: {}, | |
}, | |
}; | |
let currentContext = defaultContext; | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers: createResolvers(), | |
context: () => { | |
return createContext(options.createContextOptions)(currentContext); | |
}, | |
}); | |
const apolloTestClient = createTestClient(server); | |
return { | |
query: ({ context, ...query }: Query) => { | |
currentContext = context ?? defaultContext; | |
return apolloTestClient.query(query); | |
}, | |
mutate: ({ context, ...mutate }: Mutation) => { | |
currentContext = context ?? defaultContext; | |
return apolloTestClient.mutate(mutate); | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment