forked from mswjs/msw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response-patching.test.ts
79 lines (68 loc) · 1.87 KB
/
response-patching.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
import * as path from 'path'
import { pageWith } from 'page-with'
import type { ExecutionResult } from 'graphql'
import { buildSchema, graphql } from 'graphql'
import { ServerApi, createServer } from '@open-draft/test-server'
import { SetupWorkerApi } from 'msw'
import { gql } from '../support/graphql'
declare namespace window {
export const dispatchGraphQLQuery: (uri: string) => Promise<ExecutionResult>
export const msw: {
registration: SetupWorkerApi['start']
}
}
let httpServer: ServerApi
beforeAll(async () => {
// This test server simulates a production GraphQL server
// and uses a hard-coded `rootValue` to resolve queries
// against the schema.
httpServer = await createServer((app) => {
app.post('/graphql', async (req, res) => {
const result = await graphql({
schema: buildSchema(gql`
type User {
firstName: String!
lastName: String!
}
type Query {
user: User!
}
`),
source: req.body.query,
rootValue: {
user: {
firstName: 'John',
lastName: 'Maverick',
},
},
})
return res.status(200).json(result)
})
})
})
afterAll(async () => {
await httpServer.close()
})
function createRuntime() {
return pageWith({
example: path.join(__dirname, 'response-patching.mocks.ts'),
})
}
test('patches a GraphQL response', async () => {
const runtime = await createRuntime()
const endpointUrl = httpServer.http.makeUrl('/graphql')
await runtime.page.evaluate(() => {
return window.msw.registration
})
const res = await runtime.page.evaluate(
([url]) => {
return window.dispatchGraphQLQuery(url)
},
[endpointUrl],
)
expect(res.errors).toBeUndefined()
expect(res.data).toHaveProperty('user', {
firstName: 'Christian',
lastName: 'Maverick',
})
})