-
Notifications
You must be signed in to change notification settings - Fork 291
/
env.js
229 lines (208 loc) · 6.89 KB
/
env.js
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
// eslint-disable-next-line
import { join, basename } from "node:path";
import NodeEnvironment from "jest-environment-node";
import chalk from "chalk";
import { mkdir } from "node:fs/promises";
import { readConfig, getPuppeteer } from "./readConfig";
import filenamify from "filenamify";
const handleError = (error) => {
process.emit("uncaughtException", error);
};
const KEYS = {
CONTROL_C: "\u0003",
CONTROL_D: "\u0004",
ENTER: "\r",
};
// JEST_WORKER_ID starts at 1
const getWorkerIndex = () => process.env.JEST_WORKER_ID - 1;
const getEndpointIndex = () =>
Math.min(+process.env.BROWSERS_COUNT - 1, getWorkerIndex());
const screenshotsDirectory = join(process.cwd(), "screenshots");
const screenshot = async (page, name) => {
await mkdir(screenshotsDirectory, { recursive: true });
const filename = filenamify(`${name} (failed).jpg`);
await page.screenshot({
path: join(screenshotsDirectory, filename),
});
};
const getFullTestName = (test) => {
const names = [];
let current = test;
while (current) {
if (current.name === "ROOT_DESCRIBE_BLOCK") break;
names.unshift(current.name);
current = current.parent;
}
return names.join(" ");
};
const getErrorScreenshotName = (test, filename) => {
const fullName = getFullTestName(test);
if (!filename) return fullName;
return `${basename(filename)} - ${fullName}`;
};
class PuppeteerEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.testPath = context.testPath;
}
// 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) {
if (this.global.jasmine) {
// eslint-disable-next-line no-underscore-dangle
this.global.jasmine.DEFAULT_TIMEOUT_INTERVAL = timeout;
} else {
this.global[Symbol.for("TEST_TIMEOUT_SYMBOL")] = timeout;
}
}
async handleTestEvent(event, state) {
if (event.name === "test_fn_failure") {
await screenshot(
this.global.page,
getErrorScreenshotName(state.currentlyRunningTest, this.testPath)
);
}
}
async setup() {
const config = await readConfig();
const puppeteer = getPuppeteer();
this.global.puppeteerConfig = config;
let wsEndpoint;
try {
wsEndpoint = JSON.parse(process.env.PUPPETEER_WS_ENDPOINTS)[
getEndpointIndex()
];
} catch (e) {
throw new Error(
`wsEndpoints parse error: ${e.message} in ${process.env.PUPPETEER_WS_ENDPOINTS}`
);
}
if (!wsEndpoint) {
throw new Error("wsEndpoint not found");
}
this.global.jestPuppeteer = {
debug: async () => {
// eslint-disable-next-line no-eval
// Set timeout to 4 days
this.setTimeout(345600000);
// Run a debugger (in case Puppeteer 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(
chalk.blue("\n\n🕵️ Code is paused, press enter to resume")
);
// Run an infinite promise
return new Promise((resolve) => {
const { stdin } = process;
const onKeyPress = (key) => {
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();
}
};
const listening = stdin.listenerCount("data") > 0;
if (!listening) {
if (stdin.isTTY) {
stdin.setRawMode(true);
}
stdin.resume();
stdin.setEncoding("utf8");
}
stdin.on("data", onKeyPress);
});
},
resetPage: async () => {
if (this.global.page) {
this.global.page.removeListener("pageerror", handleError);
if (this.global.puppeteerConfig.runBeforeUnloadOnClose) {
await this.global.page.close({ runBeforeUnload: true });
} else {
await this.global.page.close();
}
}
this.global.page = await this.global.context.newPage();
if (config && config.exitOnPageError) {
this.global.page.addListener("pageerror", handleError);
}
},
resetBrowser: async () => {
if (this.global.page) {
this.global.page.removeListener("pageerror", handleError);
}
if (config.browserContext === "incognito" && this.global.context) {
await this.global.context.close();
} else if (this.global.page) {
if (this.global.puppeteerConfig.runBeforeUnloadOnClose) {
await this.global.page.close({ runBeforeUnload: true });
} else {
await this.global.page.close();
}
}
this.global.page = null;
if (this.global.browser) {
await this.global.browser.disconnect();
}
this.global.browser = await puppeteer.connect({
...config.connect,
...config.launch,
browserURL: undefined,
browserWSEndpoint: wsEndpoint,
});
if (config.browserContext === "incognito") {
// Using this, pages will be created in a pristine context.
this.global.context =
await this.global.browser.createIncognitoBrowserContext();
} else if (
config.browserContext === "default" ||
!config.browserContext
) {
/**
* Since this is a new browser, browserContexts() will return only one instance
* https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserbrowsercontexts
*/
this.global.context = await this.global.browser.browserContexts()[0];
} else {
throw new Error(
`browserContext should be either 'incognito' or 'default'. Received '${config.browserContext}'`
);
}
await this.global.jestPuppeteer.resetPage();
},
};
await this.global.jestPuppeteer.resetBrowser();
}
async teardown() {
const { page, context, browser, puppeteerConfig } = this.global;
if (page) {
page.removeListener("pageerror", handleError);
}
if (puppeteerConfig.browserContext === "incognito") {
if (context) {
await context.close();
}
} else if (page) {
if (puppeteerConfig.runBeforeUnloadOnClose) {
await page.close({ runBeforeUnload: true });
} else {
await page.close();
}
}
if (browser) {
await browser.disconnect();
}
}
}
export { PuppeteerEnvironment };