/
PlaywrightEnvironment.ts
372 lines (344 loc) · 11.4 KB
/
PlaywrightEnvironment.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/* eslint-disable no-console, @typescript-eslint/no-unused-vars */
import type {
Browser,
BrowserContext,
BrowserContextOptions,
Page,
} from 'playwright-core'
import type {
BrowserType,
ConfigDeviceType,
ConfigParams,
GenericBrowser,
JestPlaywrightConfig,
JestPlaywrightProjectConfig,
Nullable,
Playwright,
TestPlaywrightConfigOptions,
} from '../types/global'
import {
CHROMIUM,
CONFIG_ENVIRONMENT_NAME,
DEFAULT_CONFIG,
FIREFOX,
IMPORT_KIND_PLAYWRIGHT,
PERSISTENT,
LAUNCH,
} from './constants'
import {
checkDevice,
deepMerge,
formatError,
getBrowserOptions,
getBrowserType,
getDeviceBrowserType,
getPlaywrightInstance,
} from './utils'
import { saveCoverageOnPage, saveCoverageToFile } from './coverage'
const handleError = (error: Error): void => {
process.emit('uncaughtException', error)
}
const getBrowserPerProcess = async (
playwrightInstance: GenericBrowser,
browserType: BrowserType,
config: JestPlaywrightConfig,
): Promise<Browser | BrowserContext> => {
const { launchType, userDataDir, launchOptions, connectOptions } = config
if (launchType === LAUNCH || launchType === PERSISTENT) {
// https://github.com/mmarkelov/jest-playwright/issues/42#issuecomment-589170220
if (browserType !== CHROMIUM && launchOptions?.args) {
launchOptions.args = launchOptions.args.filter(
(item: string) => item !== '--no-sandbox',
)
}
const options = getBrowserOptions(browserType, launchOptions)
if (launchType === LAUNCH) {
return playwrightInstance.launch(options)
}
if (launchType === PERSISTENT) {
return playwrightInstance.launchPersistentContext(userDataDir!, options)
}
}
const options = getBrowserOptions(browserType, connectOptions)
return playwrightInstance.connect(options)
}
const getDeviceConfig = (
device: Nullable<ConfigDeviceType> | undefined,
availableDevices: Playwright['devices'],
): BrowserContextOptions => {
if (device) {
if (typeof device === 'string') {
const { defaultBrowserType, ...deviceProps } = availableDevices[device]
return deviceProps
} else {
const { name, defaultBrowserType, ...deviceProps } = device
return deviceProps
}
}
return {}
}
const getDeviceName = (
device: Nullable<ConfigDeviceType>,
): Nullable<string> => {
let deviceName: Nullable<string> = null
if (device != null) {
if (typeof device === 'string') {
deviceName = device
} else {
deviceName = device.name
}
}
return deviceName
}
export const getPlaywrightEnv = (basicEnv = 'node'): unknown => {
const RootEnv = require(basicEnv === 'node'
? 'jest-environment-node'
: 'jest-environment-jsdom')
return class PlaywrightEnvironment extends RootEnv {
readonly _config: JestPlaywrightProjectConfig
_jestPlaywrightConfig!: JestPlaywrightConfig
constructor(config: JestPlaywrightProjectConfig) {
super(config)
this._config = config
}
_getContextOptions(devices: Playwright['devices']): BrowserContextOptions {
const { browserName, device } = this._config
const browserType = getBrowserType(browserName)
const { contextOptions } = this._jestPlaywrightConfig
const deviceBrowserContextOptions = getDeviceConfig(device, devices)
const resultContextOptions = deepMerge(
deviceBrowserContextOptions,
getBrowserOptions(browserName, contextOptions),
)
if (browserType === FIREFOX && resultContextOptions.isMobile) {
console.warn(formatError(`isMobile is not supported in ${FIREFOX}.`))
delete resultContextOptions.isMobile
}
return resultContextOptions
}
_getSeparateEnvBrowserConfig(
isDebug: boolean,
config: TestPlaywrightConfigOptions,
): JestPlaywrightConfig {
const { debugOptions } = this._jestPlaywrightConfig
const defaultBrowserConfig: JestPlaywrightConfig = {
...DEFAULT_CONFIG,
launchType: LAUNCH,
}
let resultBrowserConfig: JestPlaywrightConfig = deepMerge(
defaultBrowserConfig,
config,
)
if (isDebug) {
if (debugOptions) {
resultBrowserConfig = deepMerge(resultBrowserConfig, debugOptions)
}
} else {
resultBrowserConfig = deepMerge(
this._jestPlaywrightConfig,
resultBrowserConfig,
)
}
return resultBrowserConfig
}
_getSeparateEnvContextConfig(
isDebug: boolean,
config: TestPlaywrightConfigOptions,
browserName: BrowserType,
devices: Playwright['devices'],
): BrowserContextOptions {
const { device, contextOptions } = config
const { debugOptions } = this._jestPlaywrightConfig
const deviceContextOptions: BrowserContextOptions = getDeviceConfig(
device,
devices,
)
let resultContextOptions: BrowserContextOptions = contextOptions || {}
if (isDebug) {
if (debugOptions?.contextOptions) {
resultContextOptions = deepMerge(
resultContextOptions,
debugOptions.contextOptions!,
)
}
} else {
resultContextOptions = deepMerge(
this._jestPlaywrightConfig.contextOptions!,
resultContextOptions,
)
}
resultContextOptions = deepMerge(
deviceContextOptions,
resultContextOptions,
)
return getBrowserOptions(browserName, resultContextOptions)
}
async _setNewPageInstance(context = this.global.context) {
const { exitOnPageError } = this._jestPlaywrightConfig
const page = await context.newPage()
if (exitOnPageError) {
page.on('pageerror', handleError)
}
return page
}
async setup(): Promise<void> {
const { wsEndpoint, browserName, testEnvironmentOptions } = this._config
this._jestPlaywrightConfig = testEnvironmentOptions[
CONFIG_ENVIRONMENT_NAME
] as JestPlaywrightConfig
const {
connectOptions,
collectCoverage,
selectors,
launchType,
skipInitialization,
} = this._jestPlaywrightConfig
if (wsEndpoint) {
this._jestPlaywrightConfig.connectOptions = {
...connectOptions,
wsEndpoint,
}
}
const browserType = getBrowserType(browserName)
const device = this._config.device
const deviceName: Nullable<string> = getDeviceName(device)
const {
name,
instance: playwrightInstance,
devices,
} = getPlaywrightInstance(browserType)
const contextOptions = this._getContextOptions(devices)
if (name === IMPORT_KIND_PLAYWRIGHT && selectors) {
const playwright = require('playwright')
await Promise.all(
selectors.map(({ name, script }) =>
playwright.selectors
.register(name, script)
.catch((e: Error): void => {
if (!e.toString().includes('has been already')) {
throw e
}
}),
),
)
}
this.global.browserName = browserType
this.global.deviceName = deviceName
if (!skipInitialization) {
const browserOrContext = await getBrowserPerProcess(
playwrightInstance as GenericBrowser,
browserType,
this._jestPlaywrightConfig,
)
this.global.browser =
launchType === PERSISTENT ? null : browserOrContext
this.global.context =
launchType === PERSISTENT
? browserOrContext
: await this.global.browser.newContext(contextOptions)
if (collectCoverage) {
await (this.global.context as BrowserContext).exposeFunction(
'reportCodeCoverage',
saveCoverageToFile,
)
await (this.global.context as BrowserContext).addInitScript(() =>
window.addEventListener('beforeunload', () => {
// @ts-ignore
reportCodeCoverage(window.__coverage__)
}),
)
}
this.global.page = await this._setNewPageInstance()
}
this.global.jestPlaywright = {
configSeparateEnv: async (
config: TestPlaywrightConfigOptions,
isDebug = false,
): Promise<ConfigParams> => {
const { device } = config
const browserName =
config.useDefaultBrowserType && device
? getDeviceBrowserType(device, devices) || CHROMIUM
: config.browser || browserType
const deviceName = device ? getDeviceName(device) : null
checkDevice(deviceName, devices)
const resultBrowserConfig: JestPlaywrightConfig = this._getSeparateEnvBrowserConfig(
isDebug,
config,
)
const resultContextOptions: BrowserContextOptions = this._getSeparateEnvContextConfig(
isDebug,
config,
browserName,
devices,
)
const { instance } = getPlaywrightInstance(browserName)
const browser = await getBrowserPerProcess(
instance as GenericBrowser,
browserName,
resultBrowserConfig,
)
const context = await (browser as Browser)!.newContext(
resultContextOptions,
)
const page = await context!.newPage()
return { browserName, deviceName, browser, context, page }
},
resetPage: async (): Promise<void> => {
await this.global.page?.close()
this.global.page = await this._setNewPageInstance()
},
resetContext: async (
newOptions?: BrowserContextOptions,
): Promise<void> => {
const { browser, context } = this.global
await context?.close()
const newContextOptions = newOptions
? deepMerge(contextOptions, newOptions)
: contextOptions
this.global.context = await browser.newContext(newContextOptions)
this.global.page = await this._setNewPageInstance()
},
resetBrowser: async (
newOptions?: BrowserContextOptions,
): Promise<void> => {
const { browser } = this.global
await browser?.close()
this.global.browser = await getBrowserPerProcess(
playwrightInstance as GenericBrowser,
browserType,
this._jestPlaywrightConfig,
)
const newContextOptions = newOptions
? deepMerge(contextOptions, newOptions)
: contextOptions
this.global.context = await this.global.browser.newContext(
newContextOptions,
)
this.global.page = await this._setNewPageInstance()
},
saveCoverage: async (page: Page): Promise<void> =>
saveCoverageOnPage(page, collectCoverage),
}
}
async teardown(): Promise<void> {
const { browser, context, page } = this.global
const { collectCoverage } = this._jestPlaywrightConfig
page?.removeListener('pageerror', handleError)
if (collectCoverage) {
await Promise.all(
(context as BrowserContext).pages().map((p) =>
p.close({
runBeforeUnload: true,
}),
),
)
// wait until coverage data was sent successfully to the exposed function
await new Promise((resolve) => setTimeout(resolve, 10))
}
await browser?.close()
await super.teardown()
}
}
}
export default getPlaywrightEnv()