Skip to content

Commit 259b84c

Browse files
refactor(tests): modernize getDocument with async/await and events.once
1 parent de29ef1 commit 259b84c

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

tests/e2e/helpers/global-setup.js

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const path = require("node:path");
22
const os = require("node:os");
33
const fs = require("node:fs");
4+
const { once } = require("node:events");
45
const jsdom = require("jsdom");
56

67
// global absolute root path
@@ -89,25 +90,28 @@ exports.stopApplication = async (waitTime = 100) => {
8990
}
9091
};
9192

92-
exports.getDocument = () => {
93-
return new Promise((resolve) => {
94-
const port = global.testPort || config.port || 8080;
95-
// JSDOM requires localhost instead of 0.0.0.0 for URL resolution
96-
const address = config.address === "0.0.0.0" ? "localhost" : config.address || "localhost";
97-
const url = `http://${address}:${port}`;
98-
jsdom.JSDOM.fromURL(url, { resources: "usable", runScripts: "dangerously" }).then((dom) => {
99-
dom.window.name = "jsdom";
100-
global.window = dom.window;
101-
global.document = dom.window.document;
102-
// Following fixes `navigator is not defined` errors in e2e tests, found here
103-
// https://www.appsloveworld.com/reactjs/100/37/mocha-react-navigator-is-not-defined
104-
global.navigator = {
105-
useragent: "node.js"
106-
};
107-
dom.window.fetch = fetch;
108-
resolve();
109-
});
110-
});
93+
exports.getDocument = async () => {
94+
const port = global.testPort || config.port || 8080;
95+
// JSDOM requires localhost instead of 0.0.0.0 for URL resolution
96+
const address = config.address === "0.0.0.0" ? "localhost" : config.address || "localhost";
97+
const url = `http://${address}:${port}`;
98+
99+
const dom = await jsdom.JSDOM.fromURL(url, { resources: "usable", runScripts: "dangerously" });
100+
101+
dom.window.name = "jsdom";
102+
global.window = dom.window;
103+
global.document = dom.window.document;
104+
// Some modules access navigator.*, so provide a minimal stub for JSDOM-based tests.
105+
global.navigator = {
106+
useragent: "node.js"
107+
};
108+
dom.window.fetch = fetch;
109+
110+
// fromURL() resolves when HTML is loaded, but with resources: "usable",
111+
// external scripts load asynchronously. Wait for the load event to ensure scripts are executed.
112+
if (dom.window.document.readyState !== "complete") {
113+
await once(dom.window, "load");
114+
}
111115
};
112116

113117
exports.waitForElement = (selector, ignoreValue = "", timeout = 0) => {

0 commit comments

Comments
 (0)