forked from mswjs/msw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response-patching.node.test.ts
113 lines (101 loc) · 2.83 KB
/
response-patching.node.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* @jest-environment node
*/
import { graphql } from 'msw'
import { setupServer } from 'msw/node'
import fetch from 'cross-fetch'
import { graphql as executeGraphql, buildSchema } from 'graphql'
import { ServerApi, createServer } from '@open-draft/test-server'
import { createGraphQLClient, gql } from '../support/graphql'
let httpServer: ServerApi
const server = setupServer(
graphql.query('GetUser', async (req, res, ctx) => {
const originalResponse = await ctx.fetch(req)
const { requestHeaders, queryResult } = await originalResponse.json()
return res(
ctx.data({
user: {
firstName: 'Christian',
lastName: queryResult.data?.user?.lastName,
},
// Setting the request headers on the response data on purpose
// to access them in the response of the Apollo client.
requestHeaders,
}),
ctx.errors(queryResult.errors),
)
}),
)
beforeAll(async () => {
server.listen()
// This test server acts as a production server MSW will be hitting
// when performing a request patching with `ctx.fetch()`.
httpServer = await createServer((app) => {
app.post('/graphql', async (req, res) => {
const result = await executeGraphql({
schema: buildSchema(gql`
type User {
firstName: String!
lastName: String!
}
# Describing an additional type to return
# the request headers back to the request handler.
# Apollo will strip off any extra data that
# doesn't match the query.
type RequestHeader {
name: String!
value: String!
}
type Query {
user: User!
requestHeaders: [RequestHeader!]
}
`),
operationName: 'GetUser',
source: req.body.query,
rootValue: {
user: {
firstName: 'John',
lastName: 'Maverick',
},
},
})
return res.status(200).json({
requestHeaders: req.headers,
queryResult: result,
})
})
})
})
afterAll(async () => {
server.close()
await httpServer.close()
})
test('patches a GraphQL response', async () => {
const client = createGraphQLClient({
uri: httpServer.http.makeUrl('/graphql'),
fetch,
})
const res = await client({
query: gql`
query GetUser {
user {
firstName
lastName
}
requestHeaders {
name
value
}
}
`,
})
expect(res.errors).toBeUndefined()
expect(res.data).toHaveProperty('user', {
firstName: 'Christian',
lastName: 'Maverick',
})
expect(res.data.requestHeaders).toHaveProperty('x-msw-bypass', 'true')
expect(res.data.requestHeaders).not.toHaveProperty('_headers')
expect(res.data.requestHeaders).not.toHaveProperty('_names')
})