Skip to content

Instantly share code, notes, and snippets.

@gcoda

gcoda/_test.js Secret

Created July 23, 2019 23:26
Show Gist options
  • Save gcoda/d61954334bfb1250c02fc07ca9110705 to your computer and use it in GitHub Desktop.
Save gcoda/d61954334bfb1250c02fc07ca9110705 to your computer and use it in GitHub Desktop.
apollo-server-testing with headers
const assert = require('assert').strict
const { ApolloServer, gql } = require('apollo-server-cloud-functions')
const server = new ApolloServer({
typeDefs: gql`
type Query {
field: String
}
`,
})
const { createTestClient } = require('./apollo-testing')
const { query } = createTestClient(server)
query({
query: gql`
{
__typename
}
`,
}).then(response => {
assert.deepStrictEqual(
response.body,
{ data: { __typename: 'Query' } },
'body mismatch'
)
assert.deepStrictEqual(
new Set([['content-length', '32'], ['content-type', 'application/json']]),
new Set(response.http.headers),
'Headers Mismatch'
)
})
const { print } = require('graphql/language/printer')
const { Headers } = require('node-fetch')
exports.createTestClient = server => {
const handler = server.createHandler()
const queryHandler = ({
query,
headers = {},
variables = {},
queryString,
operationName,
}) => {
return new Promise(resolve => {
handler(
{
headers: {
'content-type': 'application/json',
...headers,
},
body: {
operationName,
query: queryString || print(query),
variables,
},
method: 'POST',
mode: 'cors',
},
{
_headers: {},
_status: 0,
set(headers) {
this._headers = { ...this._headers, ...headers }
return this
},
status(status) {
this._status = status
return this
},
send(body) {
resolve({
http: {
status: this._status,
headers: new Headers({ ...this._headers }),
},
body: JSON.parse(body),
})
},
}
)
})
}
return {
query: queryHandler,
mutate: queryHandler,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment