LibWeb: Add a test-only API to spoof the current URL and origin

This is not that easy to use for test developers, as forgetting to set
the url back to its original state after testing your specific API will
cause future navigations to fail in inexplicable ways.
This commit is contained in:
Andrew Kaster
2024-09-14 21:16:46 -06:00
committed by Tim Ledbetter
parent f0270b92f1
commit acd604c5e1
5 changed files with 38 additions and 3 deletions

View File

@@ -383,12 +383,14 @@ XMLHttpRequest
XMLHttpRequestEventTarget
XMLHttpRequestUpload
XMLSerializer
__finishTest
__preventMultipleTestFunctions
animationFrame
asyncTest
printElement
println
promiseTest
spoofCurrentURL
test
timeout
webkitURL

View File

@@ -1,5 +1,6 @@
var __outputElement = null;
let __alreadyCalledTest = false;
let __originalURL = null;
function __preventMultipleTestFunctions() {
if (__alreadyCalledTest) {
throw new Error("You must only call test() or asyncTest() once per page");
@@ -10,9 +11,24 @@ function __preventMultipleTestFunctions() {
if (globalThis.internals === undefined) {
internals = {
signalTextTestIsDone: function () {},
spoofCurrentURL: function (url) {},
};
}
function __finishTest() {
if (__originalURL) {
internals.spoofCurrentURL(__originalURL);
}
internals.signalTextTestIsDone();
}
function spoofCurrentURL(url) {
if (__originalURL === null) {
__originalURL = document.location.href;
}
internals.spoofCurrentURL(url);
}
function println(s) {
__outputElement.appendChild(document.createTextNode(s + "\n"));
}
@@ -46,14 +62,14 @@ function test(f) {
__preventMultipleTestFunctions();
document.addEventListener("DOMContentLoaded", f);
window.addEventListener("load", () => {
internals.signalTextTestIsDone();
__finishTest();
});
}
function asyncTest(f) {
const done = () => {
__preventMultipleTestFunctions();
internals.signalTextTestIsDone();
__finishTest();
};
document.addEventListener("DOMContentLoaded", () => {
f(done);
@@ -64,7 +80,7 @@ function promiseTest(f) {
document.addEventListener("DOMContentLoaded", () => {
f().then(() => {
__preventMultipleTestFunctions();
internals.signalTextTestIsDone();
__finishTest();
});
});
}