-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaywright.extend.ts
317 lines (271 loc) · 8.92 KB
/
playwright.extend.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import * as crypto from 'crypto'
import { test as base, expect, type Response, Page } from '@playwright/test'
import {
Headers,
headersToObject,
flattenHeadersObject,
type FlatHeadersObject,
} from 'headers-polyfill'
import { spyOnConsole, ConsoleMessages } from 'page-with'
import { HttpServer, HttpServerMiddleware } from '@open-draft/test-server/http'
import {
Compilation,
CompilationOptions,
WebpackHttpServer,
} from 'webpack-http-server'
import { waitFor } from '../support/waitFor'
import { WorkerConsole } from './setup/workerConsole'
import { getWebpackServer } from './setup/webpackHttpServer'
export interface TestFixtures {
/**
* Create a test server instance.
*/
createServer(...middleware: Array<HttpServerMiddleware>): Promise<HttpServer>
webpackServer: WebpackHttpServer
loadExample(
entry: string | Array<string>,
options?: CompilationOptions & {
/**
* Do not await the "Mocking enabled" message in the console.
*/
skipActivation?: boolean
beforeNavigation?(compilation: Compilation): void
},
): Promise<{
compilation: Compilation
workerConsole: WorkerConsole
}>
fetch(
url: string,
init?: RequestInit,
options?: FetchOptions,
): Promise<Response>
query(uri: string, options: GraphQLQueryOptions): Promise<Response>
makeUrl(path: string): string
spyOnConsole(): ConsoleMessages
waitFor(predicate: () => unknown): Promise<void>
waitForMswActivation(): Promise<void>
}
interface FetchOptions {
page?: Page
waitForResponse?(res: Response): Promise<boolean> | boolean
}
interface GraphQLQueryOptions {
method?: 'GET' | 'POST'
query: string
variables?: Record<string, any>
multipartOptions?: GraphQLMultipartDataOptions
}
interface GraphQLMultipartDataOptions {
map: Record<string, Array<string>>
fileContents: Array<string>
}
export const test = base.extend<TestFixtures>({
async createServer({}, use) {
let server: HttpServer | undefined
await use(async (...middleware) => {
server = new HttpServer(...middleware)
await server.listen()
return server
})
await server?.close()
},
async webpackServer({}, use) {
use(await getWebpackServer())
},
async loadExample({ page, webpackServer, waitForMswActivation }, use) {
const pageExceptions: Array<Error> = []
page.on('pageerror', (error) => pageExceptions.push(error))
const workerConsole = new WorkerConsole()
let compilation: Compilation | undefined
await use(async (entry, options = {}) => {
compilation = await webpackServer.compile(
Array.prototype.concat([], entry),
options,
)
// Allow arbitrary setup code before navigating to the compilation preview.
// This is useful to set up console watchers and other side-effects.
options.beforeNavigation?.(compilation)
// Forward browser runtime errors/warnings to the test runner.
page.on('pageerror', console.error)
const oncePageReady = [
page.waitForLoadState('domcontentloaded', { timeout: 15_000 }),
page.waitForEvent('load', { timeout: 30_000 }),
page.waitForLoadState('networkidle', { timeout: 5_000 }),
]
page.goto(compilation.previewUrl)
await Promise.all(oncePageReady)
// All examlpes await the MSW activation message by default.
// Support opting-out from this behavior for tests where activation
// is not expected (e.g. when testing activation errors).
if (!options.skipActivation) {
await waitForMswActivation()
}
await workerConsole.init(page)
return {
compilation,
workerConsole,
}
})
workerConsole.removeAllListeners()
await compilation?.dispose()
},
async waitFor({}, use) {
await use(waitFor)
},
async waitForMswActivation({ spyOnConsole }, use) {
const consoleSpy = spyOnConsole()
await use(() => {
return waitFor(() => {
const groupMessages = consoleSpy.get('startGroupCollapsed')
if (groupMessages?.includes('[MSW] Mocking enabled.')) {
consoleSpy.clear()
return Promise.resolve()
}
return Promise.reject()
})
})
consoleSpy.clear()
},
async fetch({ page }, use) {
await use(async (url, init, options = {}) => {
const target = options.page || page
const requestId = crypto.randomBytes(16).toString('hex')
const fetchOptions = init || {}
const initialHeaders = fetchOptions.headers || {}
const requestHeaders = new Headers(initialHeaders)
const identityHeaderName = 'accept-language'
requestHeaders.set(identityHeaderName, requestId)
const resolvedInit = {
...fetchOptions,
headers: flattenHeadersObject(headersToObject(requestHeaders)),
}
// Don't await the request here so that we can await the response
// later on based on the request identity headers. This way we can
// perform multiple requests in parallel.
target.evaluate<unknown, [string, RequestInit]>(
([url, init]) => fetch(url, init as RequestInit),
[url, resolvedInit],
)
return target.waitForResponse(async (res) => {
if (typeof options.waitForResponse !== 'undefined') {
return options.waitForResponse(res)
}
const {
[identityHeaderName]: actualRequestId,
['x-msw-bypass']: isBypassRequest,
} = res.request().headers()
return isBypassRequest !== 'true' && actualRequestId === requestId
})
})
},
async query({ page }, use) {
await use(async (uri, options) => {
const requestId = crypto.createHash('md5').digest('hex')
const method = options.method || 'POST'
const requestUrl = new URL(uri, 'http://localhost:8080')
const headers: FlatHeadersObject = {
'x-request-id': requestId,
}
if (method === 'GET') {
requestUrl.searchParams.set('query', options.query)
if (options.variables) {
requestUrl.searchParams.set(
'variables',
JSON.stringify(options.variables),
)
}
}
const responsePromise = page.evaluate<
globalThis.Response,
{
url: string
method: string
headers: FlatHeadersObject
options: GraphQLQueryOptions
}
>(
({ url, method, headers, options }) => {
const init: RequestInit = {
method,
headers,
}
const operations = JSON.stringify({
query: options.query,
variables: options.variables,
})
function getMultipartGraphQLBody() {
if (!options.multipartOptions) {
throw new Error(
'Failed to construct a multi-part data GraphQL request: no options provided',
)
}
if (method !== 'POST') {
throw new Error(
'Cannot perform a multi-part data GraphQL request: must use "POST" method',
)
}
const body = new FormData()
body.set('operations', operations)
body.set('map', JSON.stringify(options.multipartOptions.map))
options.multipartOptions.fileContents.forEach(
(fileContent, index) => {
const file = new File([fileContent], `file${index}.txt`)
body.append(index.toString(), file)
},
)
return body
}
if (method === 'POST') {
if (!options.multipartOptions) {
headers['Content-Type'] = 'application/json'
}
init.body = options.multipartOptions
? getMultipartGraphQLBody()
: operations
}
return fetch(url, init).catch(() => {
/**
* @note Silence request rejections so that request errors
* could be asserted in tests.
*/
return new Response(null, { status: 508 })
})
},
{
url: requestUrl.href,
method,
headers,
options,
},
)
return new Promise<Response>((resolve, reject) => {
responsePromise.catch(reject)
return page
.waitForResponse(async (res) => {
const {
['x-request-id']: actualRequestId,
['x-msw-bypass']: isBypassRequest,
} = res.request().headers()
return isBypassRequest !== 'true' && actualRequestId === requestId
})
.then(resolve)
.catch(resolve)
})
})
},
async makeUrl({ webpackServer }, use) {
await use((pathname) => {
return new URL(pathname, webpackServer.serverUrl).href
})
},
async spyOnConsole({ page }, use) {
let messages: ConsoleMessages | undefined
await use(() => {
messages = spyOnConsole(page as any)
return messages
})
messages?.clear()
},
})
export { expect }