forked from redstone-finance/redstone-oracles-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-in-browser.ts
87 lines (78 loc) · 2.19 KB
/
test-in-browser.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
import { RedstoneCommon } from "@redstone-finance/utils";
import http from "http";
import { createServer } from "http-server";
import puppeteer, { ConsoleMessage, Page, Product } from "puppeteer";
export const PORT_NUMBER = 8088;
function startServer(path: string, port: number): Promise<http.Server> {
return new Promise((resolve, _) => {
const server = createServer({ root: path });
server.listen(port, "localhost", () => {
console.log(`Server is listening on http://localhost:${port}`);
resolve(server);
});
});
}
async function waitForSuccess(
page: Page,
expectedMessage: string,
port: number,
timeout: number = 2000
) {
const url = `http://localhost:${port}`;
const waitForSuccessPromise = new Promise<void>((resolve) => {
page.on("pageerror", (error: Error) => {
console.error(`${url} [error]: ${error.message}`);
throw error;
});
page.on("console", (msg: ConsoleMessage) => {
const type = msg.type();
const text = msg.text();
console.log(`${url} [${type}] ${text}`);
if (text.includes(expectedMessage)) {
resolve();
}
});
// eslint-disable-next-line @typescript-eslint/no-floating-promises
page
.goto(url)
.then(() =>
console.log(`${url} loaded successfully, waiting ${timeout} [ms]`)
);
});
await RedstoneCommon.timeout(
waitForSuccessPromise,
timeout,
`${url} didn't succeed in ${timeout} [ms].`
);
}
export async function testInBrowser(
path: string,
expectedMessage: string,
product?: Product,
port: number = PORT_NUMBER
) {
const server = await startServer(path, port);
const browser = await puppeteer.launch({
product,
protocol: product === "firefox" ? "webDriverBiDi" : undefined,
});
try {
await RedstoneCommon.retry({
fn: async () => {
const page = await browser.newPage();
return await waitForSuccess(page, expectedMessage, port);
},
maxRetries: 4,
waitBetweenMs: 1000,
backOff: {
backOffBase: 2,
},
})();
} catch (e) {
console.error(RedstoneCommon.stringifyError(e));
process.exit(1);
} finally {
await browser.close();
server.close();
}
}