forked from anishkny/playwright-test-coverage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (68 loc) · 2.37 KB
/
index.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
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const baseTest = require("@playwright/test").test;
const istanbul = require("istanbul-lib-coverage");
const istanbulTempDir = process.env.ISTANBUL_TEMP_DIR
? path.resolve(process.env.ISTANBUL_TEMP_DIR)
: path.join(process.cwd(), ".nyc_output");
function getProjectName(project) {
return project.name || "project";
}
function getProjectDir(project) {
return path.join(istanbulTempDir, getProjectName(project));
}
function generateUUID() {
return crypto.randomBytes(16).toString("hex");
}
async function collectCoverageFromFiles(coverageDir) {
const coverageFiles = await fs.promises.readdir(coverageDir);
const coverageMap = istanbul.createCoverageMap();
for (const file of coverageFiles) {
const filePath = path.join(coverageDir, file);
const fileCoverageData = await fs.promises.readFile(filePath, "utf8");
const fileCoverage = istanbul.createCoverageMap(
JSON.parse(fileCoverageData),
);
coverageMap.merge(fileCoverage);
}
return coverageMap;
}
const test = baseTest.extend({
context: async ({ context }, use, { project, testId, retry }) => {
await context.addInitScript(() =>
window.addEventListener("beforeunload", () =>
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__)),
),
);
const projectDir = getProjectDir(project);
const coverageDir = path.join(projectDir, `${testId}-${retry}`);
await fs.promises.mkdir(coverageDir, { recursive: true });
await context.exposeFunction(
"collectIstanbulCoverage",
async (coverageJSON) => {
if (coverageJSON) {
const coverageFilePath = path.join(
coverageDir,
`${generateUUID()}.json`,
);
await fs.promises.writeFile(coverageFilePath, coverageJSON);
}
},
);
await use(context);
for (const page of context.pages()) {
await page.evaluate(() =>
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__)),
);
}
const coverageMap = await collectCoverageFromFiles(coverageDir);
const coverageOutputPath = path.join(projectDir, `${testId}-${retry}.json`);
await fs.promises.writeFile(
coverageOutputPath,
JSON.stringify(coverageMap, null, 2),
);
},
});
const expect = test.expect;
module.exports = { test, expect };