-
Notifications
You must be signed in to change notification settings - Fork 73
/
PlaywrightEnvironment.ts
194 lines (182 loc) · 6.23 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
/* eslint-disable no-console */
import NodeEnvironment from 'jest-environment-node'
import { Config as JestConfig } from '@jest/types'
import {
checkBrowserEnv,
checkDeviceEnv,
getBrowserType,
getDeviceType,
getPlaywrightInstance,
readConfig,
} from './utils'
import { Config, CHROMIUM } from './constants'
import { Browser, BrowserType } from 'playwright'
const handleError = (error: Error): void => {
process.emit('uncaughtException', error)
}
const KEYS = {
CONTROL_C: '\u0003',
CONTROL_D: '\u0004',
ENTER: '\r',
}
let teardownServer: (() => Promise<void>) | null = null
let browserPerProcess: Browser | null = null
let browserShutdownTimeout: NodeJS.Timeout | null = null
const resetBrowserCloseWatchdog = (): void => {
if (browserShutdownTimeout) clearTimeout(browserShutdownTimeout)
}
// Since there are no per-worker hooks, we have to setup a timer to
// close the browser.
//
// @see https://github.com/facebook/jest/issues/8708 (and upvote plz!)
const startBrowserCloseWatchdog = (): void => {
resetBrowserCloseWatchdog()
browserShutdownTimeout = setTimeout(async () => {
const browser = browserPerProcess
browserPerProcess = null
if (browser) await browser.close()
}, 50)
}
const getBrowserPerProcess = async (
playwrightInstance: BrowserType,
config: Config,
): Promise<Browser> => {
if (!browserPerProcess) {
const browserType = getBrowserType(config)
checkBrowserEnv(browserType)
const { launchBrowserApp } = config
// https://github.com/mmarkelov/jest-playwright/issues/42#issuecomment-589170220
if (browserType !== CHROMIUM && launchBrowserApp && launchBrowserApp.args) {
launchBrowserApp.args = launchBrowserApp.args.filter(
item => item !== '--no-sandbox',
)
}
browserPerProcess = await playwrightInstance.launch(launchBrowserApp)
}
return browserPerProcess
}
class PlaywrightEnvironment extends NodeEnvironment {
private _config: JestConfig.ProjectConfig
constructor(config: JestConfig.ProjectConfig) {
super(config)
this._config = config
}
// Jest is not available here, so we have to reverse engineer
// the setTimeout function, see https://github.com/facebook/jest/blob/v23.1.0/packages/jest-runtime/src/index.js#L823
setTimeout(timeout: number): void {
if (this.global.jasmine) {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
this.global.jasmine.DEFAULT_TIMEOUT_INTERVAL = timeout
} else {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
this.global[Symbol.for('TEST_TIMEOUT_SYMBOL')] = timeout
}
}
async setup(): Promise<void> {
resetBrowserCloseWatchdog()
const config = await readConfig(this._config.rootDir)
const browserType = getBrowserType(config)
checkBrowserEnv(browserType)
const { context, server, selectors } = config
const device = getDeviceType(config)
const playwrightInstance = await getPlaywrightInstance(
browserType,
selectors,
)
let contextOptions = context
if (server) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const devServer = require('jest-dev-server')
const { setup, ERROR_TIMEOUT, ERROR_NO_COMMAND } = devServer
teardownServer = devServer.teardown
try {
await setup(config.server)
} catch (error) {
if (error.code === ERROR_TIMEOUT) {
console.log('')
console.error(error.message)
console.error(
`\n☝️ You can set "server.launchTimeout" in jest-playwright.config.js`,
)
process.exit(1)
}
if (error.code === ERROR_NO_COMMAND) {
console.log('')
console.error(error.message)
console.error(
`\n☝️ You must set "server.command" in jest-playwright.config.js`,
)
process.exit(1)
}
throw error
}
}
const availableDevices = Object.keys(playwrightInstance.devices)
if (device) {
checkDeviceEnv(device, availableDevices)
const { viewport, userAgent } = playwrightInstance.devices[device]
contextOptions = { viewport, userAgent, ...contextOptions }
}
this.global.browser = await getBrowserPerProcess(playwrightInstance, config)
this.global.context = await this.global.browser.newContext(contextOptions)
this.global.page = await this.global.context.newPage()
this.global.page.on('pageerror', handleError)
this.global.jestPlaywright = {
debug: async (): Promise<void> => {
// eslint-disable-next-line no-eval
// Set timeout to 4 days
this.setTimeout(345600000)
// Run a debugger (in case Playwright has been launched with `{ devtools: true }`)
await this.global.page.evaluate(() => {
// eslint-disable-next-line no-debugger
debugger
})
// eslint-disable-next-line no-console
console.log('\n\n🕵️ Code is paused, press enter to resume')
// Run an infinite promise
return new Promise(resolve => {
const { stdin } = process
const listening = stdin.listenerCount('data') > 0
const onKeyPress = (key: string): void => {
if (
key === KEYS.CONTROL_C ||
key === KEYS.CONTROL_D ||
key === KEYS.ENTER
) {
stdin.removeListener('data', onKeyPress)
if (!listening) {
if (stdin.isTTY) {
stdin.setRawMode(false)
}
stdin.pause()
}
resolve()
}
}
if (!listening) {
if (stdin.isTTY) {
stdin.setRawMode(true)
}
stdin.resume()
stdin.setEncoding('utf8')
}
stdin.on('data', onKeyPress)
})
},
}
}
async teardown(jestConfig: JestConfig.InitialOptions = {}): Promise<void> {
await super.teardown()
if (!jestConfig.watch && !jestConfig.watchAll && teardownServer) {
await teardownServer()
}
if (this.global.page) {
this.global.page.removeListener('pageerror', handleError)
await this.global.page.close()
}
startBrowserCloseWatchdog()
}
}
export default PlaywrightEnvironment