Skip to content

Lightpanda: the headless browser designed for AI and automation

tests: Migrate all legacy testing.async(cb) to new testing.async flow

Karl Seguin397176d868a0
diff --git a/src/browser/tests/blob.html b/src/browser/tests/blob.html
index dade9b1b7..d5964c75b 100644
--- a/src/browser/tests/blob.html
+++ b/src/browser/tests/blob.html
@@ -2,194 +2,181 @@
<meta charset="UTF-8">
<script src="./testing.js"></script>
-<script id=basic>
- {
- const parts = ["\r\nthe quick brown\rfo\rx\r", "\njumps over\r\nthe\nlazy\r", "\ndog"];
- // "transparent" ending should not modify the final buffer.
- const blob = new Blob(parts, { type: "text/html" });
-
- const expected = parts.join("");
- testing.expectEqual(expected.length, blob.size);
- testing.expectEqual("text/html", blob.type);
- testing.async(async () => { testing.expectEqual(expected, await blob.text()) });
- }
-
- {
- const parts = ["\rhello\r", "\nwor\r\nld"];
- // "native" ending should modify the final buffer.
- const blob = new Blob(parts, { endings: "native" });
-
- const expected = "\nhello\n\nwor\nld";
- testing.expectEqual(expected.length, blob.size);
- testing.async(async () => { testing.expectEqual(expected, await blob.text()) });
- }
+<script id=basic type=module>
+ const state = await testing.async();
+
+ const parts1 = ["\r\nthe quick brown\rfo\rx\r", "\njumps over\r\nthe\nlazy\r", "\ndog"];
+ // "transparent" ending should not modify the final buffer.
+ const blob1 = new Blob(parts1, { type: "text/html" });
+ const expected1 = parts1.join("");
+ const text1 = await blob1.text();
+
+ const parts2 = ["\rhello\r", "\nwor\r\nld"];
+ // "native" ending should modify the final buffer.
+ const blob2 = new Blob(parts2, { endings: "native" });
+ const expected2 = "\nhello\n\nwor\nld";
+ const text2 = await blob2.text();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(expected1.length, blob1.size);
+ testing.expectEqual("text/html", blob1.type);
+ testing.expectEqual(expected1, text1);
+
+ testing.expectEqual(expected2.length, blob2.size);
+ testing.expectEqual(expected2, text2);
+ });
</script>
<!-- Firefox and Safari only -->
-<script id=bytes>
- {
- const parts = ["light ", "panda ", "rocks ", "!"];
- const blob = new Blob(parts);
-
- testing.async(async() => {
- const expected = new Uint8Array([108, 105, 103, 104, 116, 32, 112, 97,
- 110, 100, 97, 32, 114, 111, 99, 107, 115,
- 32, 33]);
- const result = await blob.bytes();
- testing.expectEqual(true, result instanceof Uint8Array);
- testing.expectEqual(expected, result);
- });
- }
+<script id=bytes type=module>
+ const state = await testing.async();
+
+ const parts1 = ["light ", "panda ", "rocks ", "!"];
+ const blob1 = new Blob(parts1);
+ const result1 = await blob1.bytes();
// Test for SIMD.
- {
- const parts = [
- "\rThe opened package\r\nof potato\nchi\rps",
- "held the\r\nanswer to the\r mystery. Both det\rectives looke\r\rd\r",
- "\rat it but failed to realize\nit was\r\nthe\rkey\r\n",
- "\r\nto solve the \rcrime.\r"
- ];
-
- const blob = new Blob(parts, { type: "text/html", endings: "native" });
- testing.expectEqual(161, blob.size);
- testing.expectEqual("text/html", blob.type);
- testing.async(async() => {
- const expected = new Uint8Array([10, 84, 104, 101, 32, 111, 112, 101, 110,
- 101, 100, 32, 112, 97, 99, 107, 97, 103,
- 101, 10, 111, 102, 32, 112, 111, 116, 97,
- 116, 111, 10, 99, 104, 105, 10, 112, 115,
- 104, 101, 108, 100, 32, 116, 104, 101, 10,
- 97, 110, 115, 119, 101, 114, 32, 116, 111,
- 32, 116, 104, 101, 10, 32, 109, 121, 115,
- 116, 101, 114, 121, 46, 32, 66, 111, 116,
- 104, 32, 100, 101, 116, 10, 101, 99, 116,
- 105, 118, 101, 115, 32, 108, 111, 111, 107,
- 101, 10, 10, 100, 10, 10, 97, 116, 32, 105,
- 116, 32, 98, 117, 116, 32, 102, 97, 105, 108,
- 101, 100, 32, 116, 111, 32, 114, 101, 97,
- 108, 105, 122, 101, 10, 105, 116, 32, 119, 97,
- 115, 10, 116, 104, 101, 10, 107, 101, 121,
- 10, 10, 116, 111, 32, 115, 111, 108, 118, 101,
- 32, 116, 104, 101, 32, 10, 99, 114, 105, 109,
- 101, 46, 10]);
- const result = await blob.bytes();
- testing.expectEqual(true, result instanceof Uint8Array);
- testing.expectEqual(expected, result);
- });
- }
+ const parts2 = [
+ "\rThe opened package\r\nof potato\nchi\rps",
+ "held the\r\nanswer to the\r mystery. Both det\rectives looke\r\rd\r",
+ "\rat it but failed to realize\nit was\r\nthe\rkey\r\n",
+ "\r\nto solve the \rcrime.\r"
+ ];
+ const blob2 = new Blob(parts2, { type: "text/html", endings: "native" });
+ const result2 = await blob2.bytes();
+
+ state.resolve();
+ await state.done(() => {
+ const expected1 = new Uint8Array([108, 105, 103, 104, 116, 32, 112, 97,
+ 110, 100, 97, 32, 114, 111, 99, 107, 115,
+ 32, 33]);
+ testing.expectEqual(true, result1 instanceof Uint8Array);
+ testing.expectEqual(expected1, result1);
+
+ testing.expectEqual(161, blob2.size);
+ testing.expectEqual("text/html", blob2.type);
+ const expected2 = new Uint8Array([10, 84, 104, 101, 32, 111, 112, 101, 110,
+ 101, 100, 32, 112, 97, 99, 107, 97, 103,
+ 101, 10, 111, 102, 32, 112, 111, 116, 97,
+ 116, 111, 10, 99, 104, 105, 10, 112, 115,
+ 104, 101, 108, 100, 32, 116, 104, 101, 10,
+ 97, 110, 115, 119, 101, 114, 32, 116, 111,
+ 32, 116, 104, 101, 10, 32, 109, 121, 115,
+ 116, 101, 114, 121, 46, 32, 66, 111, 116,
+ 104, 32, 100, 101, 116, 10, 101, 99, 116,
+ 105, 118, 101, 115, 32, 108, 111, 111, 107,
+ 101, 10, 10, 100, 10, 10, 97, 116, 32, 105,
+ 116, 32, 98, 117, 116, 32, 102, 97, 105, 108,
+ 101, 100, 32, 116, 111, 32, 114, 101, 97,
+ 108, 105, 122, 101, 10, 105, 116, 32, 119, 97,
+ 115, 10, 116, 104, 101, 10, 107, 101, 121,
+ 10, 10, 116, 111, 32, 115, 111, 108, 118, 101,
+ 32, 116, 104, 101, 32, 10, 99, 114, 105, 109,
+ 101, 46, 10]);
+ testing.expectEqual(true, result2 instanceof Uint8Array);
+ testing.expectEqual(expected2, result2);
+ });
</script>
-<script id=parts>
+<script id=parts type=module>
+ const state = await testing.async();
+
// Blob as a blob part - contents are copied in, not stringified.
- {
- const inner = new Blob(["hello "], { type: "text/plain" });
- const blob = new Blob([inner, "world"]);
- testing.expectEqual(11, blob.size);
- testing.async(async () => {
- testing.expectEqual("hello world", await blob.text());
- });
- }
+ const inner = new Blob(["hello "], { type: "text/plain" });
+ const blobInner = new Blob([inner, "world"]);
+ const textInner = await blobInner.text();
// Uint8Array as a blob part.
- {
- const bytes = new Uint8Array([104, 101, 108, 108, 111]); // "hello"
- const blob = new Blob([bytes, " ", "world"]);
- testing.expectEqual(11, blob.size);
- testing.async(async () => {
- testing.expectEqual("hello world", await blob.text());
- });
- }
+ const bytesPart = new Uint8Array([104, 101, 108, 108, 111]); // "hello"
+ const blobBytes = new Blob([bytesPart, " ", "world"]);
+ const textBytes = await blobBytes.text();
// Non-byte TypedArrays contribute their raw backing bytes.
- {
- // Uint16Array of one element (0x0041 = 'A' little-endian) produces 2 bytes.
- const u16 = new Uint16Array([0x0041]);
- const blob = new Blob([u16]);
- testing.expectEqual(2, blob.size);
- }
+ // Uint16Array of one element (0x0041 = 'A' little-endian) produces 2 bytes.
+ const u16 = new Uint16Array([0x0041]);
+ const blobU16 = new Blob([u16]);
- {
- // Float32Array: 4 bytes per element.
- const f32 = new Float32Array([1.0, 2.0, 3.0]);
- const blob = new Blob([f32]);
- testing.expectEqual(12, blob.size);
- }
+ // Float32Array: 4 bytes per element.
+ const f32 = new Float32Array([1.0, 2.0, 3.0]);
+ const blobF32 = new Blob([f32]);
// ArrayBuffer as a blob part.
- {
- const buf = new Uint8Array([1, 2, 3, 4]).buffer;
- const blob = new Blob([buf]);
- testing.expectEqual(4, blob.size);
- testing.async(async () => {
- const result = await blob.bytes();
- testing.expectEqual(new Uint8Array([1, 2, 3, 4]), result);
- });
- }
+ const abBuf = new Uint8Array([1, 2, 3, 4]).buffer;
+ const blobAb = new Blob([abBuf]);
+ const resultAb = await blobAb.bytes();
// DataView (ArrayBufferView) as a blob part.
- {
- const buf = new Uint8Array([10, 20, 30, 40, 50]).buffer;
- const view = new DataView(buf, 1, 3); // bytes [20, 30, 40]
- const blob = new Blob([view]);
- testing.expectEqual(3, blob.size);
- testing.async(async () => {
- const result = await blob.bytes();
- testing.expectEqual(new Uint8Array([20, 30, 40]), result);
- });
- }
+ const dvBuf = new Uint8Array([10, 20, 30, 40, 50]).buffer;
+ const dvView = new DataView(dvBuf, 1, 3); // bytes [20, 30, 40]
+ const blobDv = new Blob([dvView]);
+ const resultDv = await blobDv.bytes();
// Mixed types in a single parts array.
- {
- const inner = new Blob(["bb"]);
- const bytes = new Uint8Array([99, 99]); // "cc"
- const buf = new Uint8Array([100, 100]).buffer; // "dd"
- const blob = new Blob(["aa", inner, bytes, buf, "ee"]);
- testing.expectEqual(10, blob.size);
- testing.async(async () => {
- testing.expectEqual("aabbccddee", await blob.text());
- });
- }
+ const mixedInner = new Blob(["bb"]);
+ const mixedBytes = new Uint8Array([99, 99]); // "cc"
+ const mixedBuf = new Uint8Array([100, 100]).buffer; // "dd"
+ const blobMixed = new Blob(["aa", mixedInner, mixedBytes, mixedBuf, "ee"]);
+ const textMixed = await blobMixed.text();
// Number coerces to string.
- {
- const blob = new Blob([42]);
- testing.expectEqual(2, blob.size);
- testing.async(async () => {
- testing.expectEqual("42", await blob.text());
- });
- }
+ const blobNum = new Blob([42]);
+ const textNum = await blobNum.text();
// Empty parts array.
- {
- const blob = new Blob([]);
- testing.expectEqual(0, blob.size);
- testing.expectEqual("", blob.type);
- }
+ const blobEmpty = new Blob([]);
// No arguments.
- {
- const blob = new Blob();
- testing.expectEqual(0, blob.size);
- }
+ const blobNone = new Blob();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(11, blobInner.size);
+ testing.expectEqual("hello world", textInner);
+
+ testing.expectEqual(11, blobBytes.size);
+ testing.expectEqual("hello world", textBytes);
+
+ testing.expectEqual(2, blobU16.size);
+ testing.expectEqual(12, blobF32.size);
+
+ testing.expectEqual(4, blobAb.size);
+ testing.expectEqual(new Uint8Array([1, 2, 3, 4]), resultAb);
+
+ testing.expectEqual(3, blobDv.size);
+ testing.expectEqual(new Uint8Array([20, 30, 40]), resultDv);
+
+ testing.expectEqual(10, blobMixed.size);
+ testing.expectEqual("aabbccddee", textMixed);
+
+ testing.expectEqual(2, blobNum.size);
+ testing.expectEqual("42", textNum);
+
+ testing.expectEqual(0, blobEmpty.size);
+ testing.expectEqual("", blobEmpty.type);
+
+ testing.expectEqual(0, blobNone.size);
+ });
</script>
-<script id=stream>
- {
- const parts = ["may", "thy", "knife", "chip", "and", "shatter"];
- const blob = new Blob(parts);
- const reader = blob.stream().getReader();
-
- testing.async(async () => {
- const {done: done, value: value} = await reader.read()
- const expected = new Uint8Array([109, 97, 121, 116, 104, 121, 107, 110,
- 105, 102, 101, 99, 104, 105, 112, 97,
- 110, 100, 115, 104, 97, 116, 116, 101,
- 114]);
- testing.expectEqual(false, done);
- testing.expectEqual(true, value instanceof Uint8Array);
- testing.expectEqual(expected, value);
- });
- }
+<script id=stream type=module>
+ const state = await testing.async();
+
+ const parts = ["may", "thy", "knife", "chip", "and", "shatter"];
+ const blob = new Blob(parts);
+ const reader = blob.stream().getReader();
+ const { done: done, value: value } = await reader.read();
+
+ state.resolve();
+ await state.done(() => {
+ const expected = new Uint8Array([109, 97, 121, 116, 104, 121, 107, 110,
+ 105, 102, 101, 99, 104, 105, 112, 97,
+ 110, 100, 115, 104, 97, 116, 116, 101,
+ 114]);
+ testing.expectEqual(false, done);
+ testing.expectEqual(true, value instanceof Uint8Array);
+ testing.expectEqual(expected, value);
+ });
</script>
<script id=mime_parsing>
@@ -251,40 +238,44 @@
}
</script>
-<script id=slice>
- {
- const parts = ["la", "symphonie", "des", "éclairs"];
- const blob = new Blob(parts);
- testing.async(async () => {
- const result = await blob.arrayBuffer();
- testing.expectEqual(true, result instanceof ArrayBuffer)
- });
-
- let temp = blob.slice(0);
- testing.expectEqual(blob.size, temp.size);
- testing.async(async () => {
- testing.expectEqual("lasymphoniedeséclairs", await temp.text());
- });
-
- temp = blob.slice(-4, -2, "custom");
- testing.expectEqual(2, temp.size);
+<script id=slice type=module>
+ const state = await testing.async();
+
+ const parts = ["la", "symphonie", "des", "éclairs"];
+ const blob = new Blob(parts);
+ const arrayBufferResult = await blob.arrayBuffer();
+
+ const sliceAll = blob.slice(0);
+ const sliceAllText = await sliceAll.text();
+
+ const sliceCustom = blob.slice(-4, -2, "custom");
+ const sliceCustomText = await sliceCustom.text();
+
+ const sliceTail = blob.slice(14);
+ const sliceTailText = await sliceTail.text();
+
+ const sliceMid = blob.slice(6, -10, "text/eclair");
+ const sliceMidText = await sliceMid.text();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, arrayBufferResult instanceof ArrayBuffer);
+
+ testing.expectEqual(blob.size, sliceAll.size);
+ testing.expectEqual("lasymphoniedeséclairs", sliceAllText);
+
+ testing.expectEqual(2, sliceCustom.size);
// "custom" is not a valid MIME type (no "/"), so the type is empty.
- testing.expectEqual("", temp.type);
- testing.async(async () => {
- testing.expectEqual("ai", await temp.text());
- });
-
- temp = blob.slice(14);
- testing.expectEqual(8, temp.size);
- testing.async(async () => {
- testing.expectEqual("éclairs", await temp.text());
- });
-
- temp = blob.slice(6, -10, "text/eclair");
- testing.expectEqual(6, temp.size);
- testing.expectEqual("text/eclair", temp.type);
- testing.async(async () => {
- testing.expectEqual("honied", await temp.text());
- });
- }
+ testing.expectEqual("", sliceCustom.type);
+ testing.expectEqual("ai", sliceCustomText);
+
+ testing.expectEqual(8, sliceTail.size);
+ testing.expectEqual("éclairs", sliceTailText);
+
+ testing.expectEqual(6, sliceMid.size);
+ testing.expectEqual("text/eclair", sliceMid.type);
+ testing.expectEqual("honied", sliceMidText);
+ });
</script>
+</content>
+</invoke>
diff --git a/src/browser/tests/cookie_store.html b/src/browser/tests/cookie_store.html
index bcf8b26b5..b688d6506 100644
--- a/src/browser/tests/cookie_store.html
+++ b/src/browser/tests/cookie_store.html
@@ -11,63 +11,76 @@
testing.expectEqual('function', typeof cookieStore.delete);
</script>
-<script id=set-and-get>
- testing.async(async () => {
- await cookieStore.set('user', 'lp');
- const item = await cookieStore.get('user');
+<script id=set-and-get type=module>
+ const state = await testing.async();
+ await cookieStore.set('user', 'lp');
+ const item = await cookieStore.get('user');
+ await cookieStore.delete('user');
+ const afterDelete = await cookieStore.get('user');
+ state.resolve();
+ await state.done(() => {
testing.expectEqual('user', item.name);
testing.expectEqual('lp', item.value);
testing.expectEqual('/', item.path);
testing.expectEqual('strict', item.sameSite);
testing.expectEqual(null, item.expires);
- await cookieStore.delete('user');
- testing.expectEqual(null, await cookieStore.get('user'));
+ testing.expectEqual(null, afterDelete);
});
</script>
-<script id=set-options>
- testing.async(async () => {
- await cookieStore.set({ name: 'prefs', value: 'dark', sameSite: 'lax' });
- const item = await cookieStore.get({ name: 'prefs' });
+<script id=set-options type=module>
+ const state = await testing.async();
+ await cookieStore.set({ name: 'prefs', value: 'dark', sameSite: 'lax' });
+ const item = await cookieStore.get({ name: 'prefs' });
+ await cookieStore.delete('prefs');
+ state.resolve();
+ await state.done(() => {
testing.expectEqual('prefs', item.name);
testing.expectEqual('dark', item.value);
testing.expectEqual('lax', item.sameSite);
- await cookieStore.delete('prefs');
});
</script>
-<script id=get-missing>
- testing.async(async () => {
- const item = await cookieStore.get('does-not-exist');
+<script id=get-missing type=module>
+ const state = await testing.async();
+ const item = await cookieStore.get('does-not-exist');
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(null, item);
});
</script>
-<script id=get-all>
- testing.async(async () => {
- await cookieStore.set('a', '1');
- await cookieStore.set('b', '2');
- const all = await cookieStore.getAll();
+<script id=get-all type=module>
+ const state = await testing.async();
+ await cookieStore.set('a', '1');
+ await cookieStore.set('b', '2');
+ const all = await cookieStore.getAll();
+ const names = all.map(c => c.name);
+
+ const justA = await cookieStore.getAll('a');
+
+ await cookieStore.delete('a');
+ await cookieStore.delete('b');
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(true, all.length >= 2);
- const names = all.map(c => c.name);
testing.expectEqual(true, names.includes('a'));
testing.expectEqual(true, names.includes('b'));
- const justA = await cookieStore.getAll('a');
testing.expectEqual(1, justA.length);
testing.expectEqual('a', justA[0].name);
testing.expectEqual('1', justA[0].value);
-
- await cookieStore.delete('a');
- await cookieStore.delete('b');
});
</script>
-<script id=delete-options>
- testing.async(async () => {
- await cookieStore.set('tmp', 'x');
- await cookieStore.delete({ name: 'tmp' });
- testing.expectEqual(null, await cookieStore.get('tmp'));
+<script id=delete-options type=module>
+ const state = await testing.async();
+ await cookieStore.set('tmp', 'x');
+ await cookieStore.delete({ name: 'tmp' });
+ const item = await cookieStore.get('tmp');
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(null, item);
});
</script>
@@ -86,139 +99,170 @@
testing.expectEqual(0, ev.deleted.length);
</script>
-<script id=change-event-from-cookieStore-set>
- testing.async(async () => {
- const events = [];
- const handler = (e) => events.push(e);
- cookieStore.addEventListener('change', handler);
+<script id=change-event-from-cookieStore-set type=module>
+ const state = await testing.async();
+ const events = [];
+ const handler = (e) => events.push(e);
+ cookieStore.addEventListener('change', handler);
+
+ await cookieStore.set('ev-from-set', 'v1');
+ // Spec says change events are queued tasks — yield to the loop.
+ await new Promise(r => setTimeout(r, 0));
- await cookieStore.set('ev-from-set', 'v1');
- // Spec says change events are queued tasks — yield to the loop.
- await new Promise(r => setTimeout(r, 0));
+ const lenAfterSet = events.length;
- testing.expectEqual(1, events.length);
+ await cookieStore.delete('ev-from-set');
+ await new Promise(r => setTimeout(r, 0));
+
+ const lenAfterDelete = events.length;
+
+ cookieStore.removeEventListener('change', handler);
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(1, lenAfterSet);
testing.expectEqual(1, events[0].changed.length);
testing.expectEqual('ev-from-set', events[0].changed[0].name);
testing.expectEqual('v1', events[0].changed[0].value);
testing.expectEqual(0, events[0].deleted.length);
- await cookieStore.delete('ev-from-set');
- await new Promise(r => setTimeout(r, 0));
-
- testing.expectEqual(2, events.length);
+ testing.expectEqual(2, lenAfterDelete);
testing.expectEqual(0, events[1].changed.length);
testing.expectEqual(1, events[1].deleted.length);
testing.expectEqual('ev-from-set', events[1].deleted[0].name);
-
- cookieStore.removeEventListener('change', handler);
});
</script>
-<script id=set-rejects-invalid-input>
- testing.async(async () => {
- const expectReject = async (label, init, valueArg) => {
- try {
- if (valueArg !== undefined) {
- await cookieStore.set(init, valueArg);
- } else {
- await cookieStore.set(init);
- }
- testing.fail(`expected ${label} to reject`);
- } catch (err) {
- testing.expectEqual('TypeError', err.name);
+<script id=set-rejects-invalid-input type=module>
+ const state = await testing.async();
+ // Capture the rejection's error name (or null if it unexpectedly resolved).
+ const captureReject = async (init, valueArg) => {
+ try {
+ if (valueArg !== undefined) {
+ await cookieStore.set(init, valueArg);
+ } else {
+ await cookieStore.set(init);
}
- };
-
- // Empty name only rejects when the value is empty too or carries an '='.
- // A nameless cookie with an ordinary value is valid (cf. `Set-Cookie: =v`).
- await expectReject('empty name and empty value', '', '');
- await expectReject('empty name with = in value', '', 'a=b');
+ return null;
+ } catch (err) {
+ return err.name;
+ }
+ };
+
+ // Empty name only rejects when the value is empty too or carries an '='.
+ // A nameless cookie with an ordinary value is valid (cf. `Set-Cookie: =v`).
+ const rejects = [
+ await captureReject('', ''),
+ await captureReject('', 'a=b'),
// Forbidden chars in name.
- await expectReject('name with =', 'a=b', 'v');
- await expectReject('name with ;', 'a;b', 'v');
- await expectReject('name with newline', 'a\nb', 'v');
+ await captureReject('a=b', 'v'),
+ await captureReject('a;b', 'v'),
+ await captureReject('a\nb', 'v'),
// Forbidden chars in value.
- await expectReject('value with ;', 'k', 'v;injected=1');
- await expectReject('value with CR', 'k', 'v\rinjected');
+ await captureReject('k', 'v;injected=1'),
+ await captureReject('k', 'v\rinjected'),
// Forbidden chars in path / domain.
- await expectReject('path with ;', { name: 'k', value: 'v', path: '/;evil' });
- await expectReject('domain with newline', { name: 'k', value: 'v', domain: 'bad\n.example' });
-
- // A nameless cookie with an ordinary value is accepted, and delete('')
- // targets it without rejecting on the empty name.
- await cookieStore.set('', 'nameless');
- testing.expectEqual('nameless', (await cookieStore.get('')).value);
- await cookieStore.delete('');
- testing.expectEqual(null, await cookieStore.get(''));
-
- // A clean call still works after the rejections.
- await cookieStore.set('after-validation', 'ok');
- const item = await cookieStore.get('after-validation');
+ await captureReject({ name: 'k', value: 'v', path: '/;evil' }),
+ await captureReject({ name: 'k', value: 'v', domain: 'bad\n.example' }),
+ ];
+
+ // A nameless cookie with an ordinary value is accepted, and delete('')
+ // targets it without rejecting on the empty name.
+ await cookieStore.set('', 'nameless');
+ const namelessValue = (await cookieStore.get('')).value;
+ await cookieStore.delete('');
+ const afterNamelessDelete = await cookieStore.get('');
+
+ // A clean call still works after the rejections.
+ await cookieStore.set('after-validation', 'ok');
+ const item = await cookieStore.get('after-validation');
+ await cookieStore.delete('after-validation');
+
+ state.resolve();
+ await state.done(() => {
+ for (const name of rejects) {
+ testing.expectEqual('TypeError', name);
+ }
+ testing.expectEqual('nameless', namelessValue);
+ testing.expectEqual(null, afterNamelessDelete);
testing.expectEqual('ok', item.value);
- await cookieStore.delete('after-validation');
});
</script>
-<script id=change-event-delete-omits-value>
- testing.async(async () => {
- const events = [];
- const handler = (e) => events.push(e);
- cookieStore.addEventListener('change', handler);
+<script id=change-event-delete-omits-value type=module>
+ const state = await testing.async();
+ const events = [];
+ const handler = (e) => events.push(e);
+ cookieStore.addEventListener('change', handler);
- await cookieStore.set('ev-delete-val', 'original');
- await new Promise(r => setTimeout(r, 0));
+ await cookieStore.set('ev-delete-val', 'original');
+ await new Promise(r => setTimeout(r, 0));
- // Sanity: the change event must report the value that was stored.
- testing.expectEqual('original', events[0].changed[0].value);
+ // Sanity: the change event must report the value that was stored.
+ const setValue = events[0].changed[0].value;
- await cookieStore.delete('ev-delete-val');
- await new Promise(r => setTimeout(r, 0));
+ await cookieStore.delete('ev-delete-val');
+ await new Promise(r => setTimeout(r, 0));
+ const deletedLength = events[1].deleted.length;
+ const deletedName = events[1].deleted[0].name;
+ const deletedValue = events[1].deleted[0].value;
+
+ cookieStore.removeEventListener('change', handler);
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('original', setValue);
// Per spec, deletion change events identify the removed cookie by name
// but carry no value (it is reported as undefined).
- testing.expectEqual(1, events[1].deleted.length);
- testing.expectEqual('ev-delete-val', events[1].deleted[0].name);
- testing.expectEqual(undefined, events[1].deleted[0].value);
-
- cookieStore.removeEventListener('change', handler);
+ testing.expectEqual(1, deletedLength);
+ testing.expectEqual('ev-delete-val', deletedName);
+ testing.expectEqual(undefined, deletedValue);
});
</script>
-<script id=change-event-from-document-cookie>
- testing.async(async () => {
- const events = [];
- const handler = (e) => events.push(e);
- cookieStore.addEventListener('change', handler);
+<script id=change-event-from-document-cookie type=module>
+ const state = await testing.async();
+ const events = [];
+ const handler = (e) => events.push(e);
+ cookieStore.addEventListener('change', handler);
+
+ document.cookie = 'ev-from-doc=v1; path=/';
+ await new Promise(r => setTimeout(r, 0));
+
+ const lenAfterSet = events.length;
- document.cookie = 'ev-from-doc=v1; path=/';
- await new Promise(r => setTimeout(r, 0));
+ document.cookie = 'ev-from-doc=DELETED; path=/; max-age=0';
+ await new Promise(r => setTimeout(r, 0));
- testing.expectEqual(1, events.length);
+ const lenAfterDelete = events.length;
+
+ cookieStore.removeEventListener('change', handler);
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(1, lenAfterSet);
testing.expectEqual('ev-from-doc', events[0].changed[0].name);
testing.expectEqual('v1', events[0].changed[0].value);
- document.cookie = 'ev-from-doc=DELETED; path=/; max-age=0';
- await new Promise(r => setTimeout(r, 0));
-
- testing.expectEqual(2, events.length);
+ testing.expectEqual(2, lenAfterDelete);
testing.expectEqual('ev-from-doc', events[1].deleted[0].name);
-
- cookieStore.removeEventListener('change', handler);
});
</script>
-<script id=change-event-onchange-attribute>
- testing.async(async () => {
- let captured = null;
- cookieStore.onchange = (e) => { captured = e; };
+<script id=change-event-onchange-attribute type=module>
+ const state = await testing.async();
+ let captured = null;
+ cookieStore.onchange = (e) => { captured = e; };
- await cookieStore.set('ev-onchange', 'v1');
- await new Promise(r => setTimeout(r, 0));
+ await cookieStore.set('ev-onchange', 'v1');
+ await new Promise(r => setTimeout(r, 0));
- testing.expectEqual(true, captured !== null);
- testing.expectEqual('ev-onchange', captured.changed[0].name);
+ const wasCaptured = captured !== null;
+ const capturedName = captured ? captured.changed[0].name : null;
- cookieStore.onchange = null;
- await cookieStore.delete('ev-onchange');
+ cookieStore.onchange = null;
+ await cookieStore.delete('ev-onchange');
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, wasCaptured);
+ testing.expectEqual('ev-onchange', capturedName);
});
</script>
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index d1b37f2b5..b9bbe4aba 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -63,267 +63,316 @@
testing.expectEqual(true, crypto.subtle instanceof SubtleCrypto);
</script>
-<script id=sign-and-verify-hmac>
- testing.async(async () => {
- let key = await crypto.subtle.generateKey(
- {
- name: "HMAC",
- hash: { name: "SHA-512" },
- },
- true,
- ["sign", "verify"],
- );
-
+<script id=sign-and-verify-hmac type=module>
+ const state = await testing.async();
+ let key = await crypto.subtle.generateKey(
+ {
+ name: "HMAC",
+ hash: { name: "SHA-512" },
+ },
+ true,
+ ["sign", "verify"],
+ );
+
+ const raw = await crypto.subtle.exportKey("raw", key);
+
+ const encoder = new TextEncoder();
+
+ const signature = await crypto.subtle.sign(
+ "HMAC",
+ key,
+ encoder.encode("Hello, world!")
+ );
+
+ const result = await window.crypto.subtle.verify(
+ { name: "HMAC" },
+ key,
+ signature,
+ encoder.encode("Hello, world!")
+ );
+
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(true, key instanceof CryptoKey);
-
- const raw = await crypto.subtle.exportKey("raw", key);
testing.expectEqual(128, raw.byteLength);
-
- const encoder = new TextEncoder();
-
- const signature = await crypto.subtle.sign(
- "HMAC",
- key,
- encoder.encode("Hello, world!")
- );
-
testing.expectEqual(true, signature instanceof ArrayBuffer);
-
- const result = await window.crypto.subtle.verify(
- { name: "HMAC" },
- key,
- signature,
- encoder.encode("Hello, world!")
- );
-
testing.expectEqual(true, result);
});
</script>
-<script id=derive-shared-key-x25519>
- testing.async(async () => {
- const { privateKey, publicKey } = await crypto.subtle.generateKey(
- { name: "X25519" },
- true,
- ["deriveBits"],
- );
-
+<script id=derive-shared-key-x25519 type=module>
+ const state = await testing.async();
+ const { privateKey, publicKey } = await crypto.subtle.generateKey(
+ { name: "X25519" },
+ true,
+ ["deriveBits"],
+ );
+
+ const sharedKey = await crypto.subtle.deriveBits(
+ {
+ name: "X25519",
+ public: publicKey,
+ },
+ privateKey,
+ 128,
+ );
+
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(true, privateKey instanceof CryptoKey);
testing.expectEqual(true, publicKey instanceof CryptoKey);
-
- const sharedKey = await crypto.subtle.deriveBits(
- {
- name: "X25519",
- public: publicKey,
- },
- privateKey,
- 128,
- );
-
testing.expectEqual(16, sharedKey.byteLength);
});
</script>
-<script id=aes-ctr-counter-wrap>
- testing.async(async () => {
- // AES-CTR must increment only the rightmost `length` bits of the counter
- // block and leave the nonce bits fixed when that sub-counter wraps. Use a
- // 1-bit counter so it wraps after two blocks, and check each block's
- // keystream against an independent single-block encryption (the
- // non-wrapping path, used here as the oracle).
- const key = await crypto.subtle.importKey(
- "raw", new Uint8Array(16), { name: "AES-CTR" }, false, ["encrypt", "decrypt"],
- );
-
- // Counter with the low bit set; the wrap target is the same block with the
- // low bit cleared (which differs from a naive +1 carry).
- const counter = new Uint8Array(16); counter[15] = 0x01;
- const counter0 = new Uint8Array(16);
-
- const enc = (ctr, bits, data) =>
- crypto.subtle.encrypt({ name: "AES-CTR", counter: ctr, length: bits }, key, data);
-
- const ks1 = new Uint8Array(await enc(counter, 128, new Uint8Array(16)));
- const ks2 = new Uint8Array(await enc(counter0, 128, new Uint8Array(16)));
- const full = new Uint8Array(await enc(counter, 1, new Uint8Array(32)));
+<script id=aes-ctr-counter-wrap type=module>
+ const state = await testing.async();
+ // AES-CTR must increment only the rightmost `length` bits of the counter
+ // block and leave the nonce bits fixed when that sub-counter wraps. Use a
+ // 1-bit counter so it wraps after two blocks, and check each block's
+ // keystream against an independent single-block encryption (the
+ // non-wrapping path, used here as the oracle).
+ const key = await crypto.subtle.importKey(
+ "raw", new Uint8Array(16), { name: "AES-CTR" }, false, ["encrypt", "decrypt"],
+ );
+
+ // Counter with the low bit set; the wrap target is the same block with the
+ // low bit cleared (which differs from a naive +1 carry).
+ const counter = new Uint8Array(16); counter[15] = 0x01;
+ const counter0 = new Uint8Array(16);
+
+ const enc = (ctr, bits, data) =>
+ crypto.subtle.encrypt({ name: "AES-CTR", counter: ctr, length: bits }, key, data);
+
+ const ks1 = new Uint8Array(await enc(counter, 128, new Uint8Array(16)));
+ const ks2 = new Uint8Array(await enc(counter0, 128, new Uint8Array(16)));
+ const full = new Uint8Array(await enc(counter, 1, new Uint8Array(32)));
+
+ // A message longer than the counter space (here 2 blocks for a 1-bit
+ // counter) must reject rather than reuse counter values.
+ let overLengthError = null;
+ try {
+ await enc(counter0, 1, new Uint8Array(48));
+ } catch (err) {
+ overLengthError = err;
+ }
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(ks1.join(","), full.slice(0, 16).join(","));
testing.expectEqual(ks2.join(","), full.slice(16).join(","));
- // A message longer than the counter space (here 2 blocks for a 1-bit
- // counter) must reject rather than reuse counter values.
- try {
- await enc(counter0, 1, new Uint8Array(48));
- testing.fail("expected AES-CTR over-length to reject");
- } catch (err) {
- testing.expectEqual("OperationError", err.name);
- }
+ testing.expectEqual(true, overLengthError !== null);
+ testing.expectEqual("OperationError", overLengthError.name);
});
</script>
-<script id=hmac-verify-length-mismatch>
- testing.async(async () => {
- // A signature whose length differs from the MAC resolves to false rather
- // than rejecting (and a truncated-but-matching prefix must not pass).
- const key = await crypto.subtle.generateKey(
- { name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"],
- );
- const data = new TextEncoder().encode("over 9000");
- const sig = await crypto.subtle.sign("HMAC", key, data);
-
- testing.expectEqual(true, await crypto.subtle.verify("HMAC", key, sig, data));
- testing.expectEqual(false, await crypto.subtle.verify("HMAC", key, sig.slice(0, 16), data));
+<script id=hmac-verify-length-mismatch type=module>
+ const state = await testing.async();
+ // A signature whose length differs from the MAC resolves to false rather
+ // than rejecting (and a truncated-but-matching prefix must not pass).
+ const key = await crypto.subtle.generateKey(
+ { name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"],
+ );
+ const data = new TextEncoder().encode("over 9000");
+ const sig = await crypto.subtle.sign("HMAC", key, data);
+
+ const verifyFull = await crypto.subtle.verify("HMAC", key, sig, data);
+ const verifyTruncated = await crypto.subtle.verify("HMAC", key, sig.slice(0, 16), data);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, verifyFull);
+ testing.expectEqual(false, verifyTruncated);
});
</script>
<script>
- // helper
- window.expectGenKeyRejects = async function(algo, extractable, usages, expected) {
+ // helper: runs generateKey and captures the rejection's error name (or null
+ // if it unexpectedly resolved). Returns { algo, expected, actual } so the
+ // caller can assert synchronously inside state.done.
+ window.captureGenKeyReject = async function(algo, extractable, usages, expected) {
try {
await crypto.subtle.generateKey(algo, extractable, usages);
- testing.fail(`expected ${expected}, but generateKey resolved for ${JSON.stringify(algo)}`);
+ return { algo, expected, actual: null };
} catch (err) {
- testing.expectEqual(expected, err.name);
+ return { algo, expected, actual: err.name };
+ }
+ };
+
+ // assert a list of capture results synchronously.
+ window.assertGenKeyRejects = function(results) {
+ for (const r of results) {
+ testing.expectEqual(r.expected, r.actual);
}
};
</script>
-<script id=generateKey-unrecognized-algorithm>
- testing.async(async () => {
- // Unknown name (string and object form) -> NotSupportedError.
- await expectGenKeyRejects("AES", true, ["encrypt"], "NotSupportedError");
- await expectGenKeyRejects({ name: "AES" }, true, ["encrypt"], "NotSupportedError");
- await expectGenKeyRejects({ name: "AES-CMAC", length: 128 }, true, ["encrypt"], "NotSupportedError");
- await expectGenKeyRejects({ name: "EC", namedCurve: "P-256" }, true, ["sign"], "NotSupportedError");
- // Empty algorithm dictionary -> TypeError (missing required `name`).
- await expectGenKeyRejects({}, true, ["encrypt"], "TypeError");
+<script id=generateKey-unrecognized-algorithm type=module>
+ const state = await testing.async();
+ // Unknown name (string and object form) -> NotSupportedError.
+ // Empty algorithm dictionary -> TypeError (missing required `name`).
+ const results = [
+ await captureGenKeyReject("AES", true, ["encrypt"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "AES" }, true, ["encrypt"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "AES-CMAC", length: 128 }, true, ["encrypt"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "EC", namedCurve: "P-256" }, true, ["sign"], "NotSupportedError"),
+ await captureGenKeyReject({}, true, ["encrypt"], "TypeError"),
+ ];
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
});
</script>
-<script id=generateKey-aes-validation>
- testing.async(async () => {
- // Bad usages: SyntaxError.
- await expectGenKeyRejects({ name: "AES-CBC", length: 128 }, true, ["sign"], "SyntaxError");
- await expectGenKeyRejects({ name: "AES-GCM", length: 128 }, true, ["encrypt", "deriveBits"], "SyntaxError");
- // AES-KW only allows wrapKey / unwrapKey.
- await expectGenKeyRejects({ name: "AES-KW", length: 128 }, true, ["encrypt"], "SyntaxError");
-
- // Bad length: OperationError.
- for (const length of [64, 127, 129, 255, 257, 512]) {
- await expectGenKeyRejects({ name: "AES-CBC", length }, true, ["encrypt"], "OperationError");
- }
+<script id=generateKey-aes-validation type=module>
+ const state = await testing.async();
+ const results = [];
+ // Bad usages: SyntaxError.
+ results.push(await captureGenKeyReject({ name: "AES-CBC", length: 128 }, true, ["sign"], "SyntaxError"));
+ results.push(await captureGenKeyReject({ name: "AES-GCM", length: 128 }, true, ["encrypt", "deriveBits"], "SyntaxError"));
+ // AES-KW only allows wrapKey / unwrapKey.
+ results.push(await captureGenKeyReject({ name: "AES-KW", length: 128 }, true, ["encrypt"], "SyntaxError"));
+
+ // Bad length: OperationError.
+ for (const length of [64, 127, 129, 255, 257, 512]) {
+ results.push(await captureGenKeyReject({ name: "AES-CBC", length }, true, ["encrypt"], "OperationError"));
+ }
+
+ // Empty usages on a secret key: SyntaxError.
+ results.push(await captureGenKeyReject({ name: "AES-CBC", length: 128 }, true, [], "SyntaxError"));
+ results.push(await captureGenKeyReject({ name: "AES-KW", length: 256 }, true, [], "SyntaxError"));
- // Empty usages on a secret key: SyntaxError.
- await expectGenKeyRejects({ name: "AES-CBC", length: 128 }, true, [], "SyntaxError");
- await expectGenKeyRejects({ name: "AES-KW", length: 256 }, true, [], "SyntaxError");
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
});
</script>
-<script id=generateKey-ec-validation>
- testing.async(async () => {
- // Bad usages: SyntaxError.
- await expectGenKeyRejects({ name: "ECDSA", namedCurve: "P-256" }, true, ["encrypt"], "SyntaxError");
- await expectGenKeyRejects({ name: "ECDH", namedCurve: "P-256" }, true, ["sign"], "SyntaxError");
-
- // Unknown curve: NotSupportedError (not OperationError, per spec).
- await expectGenKeyRejects({ name: "ECDSA", namedCurve: "P-512" }, true, ["sign"], "NotSupportedError");
- await expectGenKeyRejects({ name: "ECDH", namedCurve: "Curve25519" }, true, ["deriveBits"], "NotSupportedError");
-
- // Empty usages: SyntaxError (mandatoryUsages aside, the spec rejects empty for private keys).
- await expectGenKeyRejects({ name: "ECDSA", namedCurve: "P-256" }, true, [], "SyntaxError");
+<script id=generateKey-ec-validation type=module>
+ const state = await testing.async();
+ // Bad usages: SyntaxError.
+ // Unknown curve: NotSupportedError (not OperationError, per spec).
+ // Empty usages: SyntaxError (mandatoryUsages aside, the spec rejects empty for private keys).
+ const results = [
+ await captureGenKeyReject({ name: "ECDSA", namedCurve: "P-256" }, true, ["encrypt"], "SyntaxError"),
+ await captureGenKeyReject({ name: "ECDH", namedCurve: "P-256" }, true, ["sign"], "SyntaxError"),
+ await captureGenKeyReject({ name: "ECDSA", namedCurve: "P-512" }, true, ["sign"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "ECDH", namedCurve: "Curve25519" }, true, ["deriveBits"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "ECDSA", namedCurve: "P-256" }, true, [], "SyntaxError"),
+ ];
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
});
</script>
-<script id=generateKey-rsa-validation>
- testing.async(async () => {
- const goodExp = new Uint8Array([1, 0, 1]); // 65537
+<script id=generateKey-rsa-validation type=module>
+ const state = await testing.async();
+ const goodExp = new Uint8Array([1, 0, 1]); // 65537
+ const results = [
// Bad name: NotSupportedError.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSA", hash: "SHA-256", modulusLength: 2048, publicExponent: goodExp },
true, ["sign"], "NotSupportedError",
- );
-
+ ),
// Bad hash: NotSupportedError.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSA-PSS", hash: "SHA", modulusLength: 2048, publicExponent: goodExp },
true, ["sign"], "NotSupportedError",
- );
-
+ ),
// Bad usages: SyntaxError. RSASSA only allows sign/verify.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", modulusLength: 2048, publicExponent: goodExp },
true, ["encrypt"], "SyntaxError",
- );
+ ),
// RSA-OAEP only allows encrypt/decrypt/wrapKey/unwrapKey.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSA-OAEP", hash: "SHA-256", modulusLength: 2048, publicExponent: goodExp },
true, ["sign"], "SyntaxError",
- );
-
+ ),
// Bad publicExponent: OperationError.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSA-OAEP", hash: "SHA-256", modulusLength: 2048, publicExponent: new Uint8Array([1]) },
true, ["encrypt"], "OperationError",
- );
- await expectGenKeyRejects(
+ ),
+ await captureGenKeyReject(
{ name: "RSA-OAEP", hash: "SHA-256", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 0]) },
true, ["encrypt"], "OperationError",
- );
-
+ ),
// Empty usages: SyntaxError.
- await expectGenKeyRejects(
+ await captureGenKeyReject(
{ name: "RSA-OAEP", hash: "SHA-256", modulusLength: 2048, publicExponent: goodExp },
true, [], "SyntaxError",
- );
+ ),
+ ];
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
});
</script>
-<script id=generateKey-hmac-validation>
- testing.async(async () => {
- // Unknown hash: NotSupportedError.
- await expectGenKeyRejects({ name: "HMAC", hash: "MD5" }, true, ["sign"], "NotSupportedError");
-
- // Bad usages: SyntaxError. HMAC only allows sign/verify.
- await expectGenKeyRejects({ name: "HMAC", hash: "SHA-256" }, true, ["encrypt"], "SyntaxError");
- await expectGenKeyRejects({ name: "HMAC", hash: "SHA-256" }, true, ["sign", "deriveBits"], "SyntaxError");
-
- // Empty usages: SyntaxError.
- await expectGenKeyRejects({ name: "HMAC", hash: "SHA-256" }, true, [], "SyntaxError");
-
- // A present, zero length is an OperationError (not a zero-byte key).
- await expectGenKeyRejects({ name: "HMAC", hash: "SHA-256", length: 0 }, true, ["sign"], "OperationError");
-
- // An explicit length overrides the hash block size (256 bits -> 32 bytes).
- const sized = await crypto.subtle.generateKey(
- { name: "HMAC", hash: "SHA-256", length: 256 }, true, ["sign", "verify"],
- );
- testing.expectEqual(32, (await crypto.subtle.exportKey("raw", sized)).byteLength);
+<script id=generateKey-hmac-validation type=module>
+ const state = await testing.async();
+ // Unknown hash: NotSupportedError.
+ // Bad usages: SyntaxError. HMAC only allows sign/verify.
+ // Empty usages: SyntaxError.
+ // A present, zero length is an OperationError (not a zero-byte key).
+ const results = [
+ await captureGenKeyReject({ name: "HMAC", hash: "MD5" }, true, ["sign"], "NotSupportedError"),
+ await captureGenKeyReject({ name: "HMAC", hash: "SHA-256" }, true, ["encrypt"], "SyntaxError"),
+ await captureGenKeyReject({ name: "HMAC", hash: "SHA-256" }, true, ["sign", "deriveBits"], "SyntaxError"),
+ await captureGenKeyReject({ name: "HMAC", hash: "SHA-256" }, true, [], "SyntaxError"),
+ await captureGenKeyReject({ name: "HMAC", hash: "SHA-256", length: 0 }, true, ["sign"], "OperationError"),
+ ];
+
+ // An explicit length overrides the hash block size (256 bits -> 32 bytes).
+ const sized = await crypto.subtle.generateKey(
+ { name: "HMAC", hash: "SHA-256", length: 256 }, true, ["sign", "verify"],
+ );
+ const sizedRaw = await crypto.subtle.exportKey("raw", sized);
+
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
+ testing.expectEqual(32, sizedRaw.byteLength);
});
</script>
-<script id=generateKey-edxxx-validation>
- testing.async(async () => {
- // Ed25519 / Ed448 only allow sign/verify; X448 only allows deriveKey/deriveBits.
- await expectGenKeyRejects("Ed25519", true, ["encrypt"], "SyntaxError");
- await expectGenKeyRejects({ name: "Ed448" }, true, ["deriveBits"], "SyntaxError");
- await expectGenKeyRejects("X448", true, ["sign"], "SyntaxError");
-
- // Empty usages: SyntaxError.
- await expectGenKeyRejects("Ed25519", true, [], "SyntaxError");
+<script id=generateKey-edxxx-validation type=module>
+ const state = await testing.async();
+ // Ed25519 / Ed448 only allow sign/verify; X448 only allows deriveKey/deriveBits.
+ // Empty usages: SyntaxError.
+ const results = [
+ await captureGenKeyReject("Ed25519", true, ["encrypt"], "SyntaxError"),
+ await captureGenKeyReject({ name: "Ed448" }, true, ["deriveBits"], "SyntaxError"),
+ await captureGenKeyReject("X448", true, ["sign"], "SyntaxError"),
+ await captureGenKeyReject("Ed25519", true, [], "SyntaxError"),
+ ];
+ state.resolve();
+ await state.done(() => {
+ assertGenKeyRejects(results);
});
</script>
-<script id="digest">
- testing.async(async () => {
- async function hash(algo, data) {
- const buffer = await window.crypto.subtle.digest(algo, new TextEncoder().encode(data));
- return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
- }
- testing.expectEqual("a6a1e3375239f215f09a156df29c17c7d1ac6722", await hash('sha-1', 'over 9000'));
- testing.expectEqual("1bc375bb92459685194dda18a4b835f4e2972ec1bde6d9ab3db53fcc584a6580", await hash('sha-256', 'over 9000'));
- testing.expectEqual("a4260d64c2eea9fd30c1f895c5e48a26d817e19d3a700b61b3ce665864ff4b8e012bd357d345aa614c5f642dab865ea1", await hash('sha-384', 'over 9000'));
- testing.expectEqual("6cad17e6f3f76680d6dd18ed043b75b4f6e1aa1d08b917294942e882fb6466c3510948c34af8b903ed0725b582b3b39c0e485ae2c1b7dfdb192ee38b79c782b6", await hash('sha-512', 'over 9000'));
+<script id="digest" type=module>
+ const state = await testing.async();
+ async function hash(algo, data) {
+ const buffer = await window.crypto.subtle.digest(algo, new TextEncoder().encode(data));
+ return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
+ }
+ const sha1 = await hash('sha-1', 'over 9000');
+ const sha256 = await hash('sha-256', 'over 9000');
+ const sha384 = await hash('sha-384', 'over 9000');
+ const sha512 = await hash('sha-512', 'over 9000');
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("a6a1e3375239f215f09a156df29c17c7d1ac6722", sha1);
+ testing.expectEqual("1bc375bb92459685194dda18a4b835f4e2972ec1bde6d9ab3db53fcc584a6580", sha256);
+ testing.expectEqual("a4260d64c2eea9fd30c1f895c5e48a26d817e19d3a700b61b3ce665864ff4b8e012bd357d345aa614c5f642dab865ea1", sha384);
+ testing.expectEqual("6cad17e6f3f76680d6dd18ed043b75b4f6e1aa1d08b917294942e882fb6466c3510948c34af8b903ed0725b582b3b39c0e485ae2c1b7dfdb192ee38b79c782b6", sha512);
});
</script>
diff --git a/src/browser/tests/css/external_stylesheet.html b/src/browser/tests/css/external_stylesheet.html
index a98520ada..4a2b19bdd 100644
--- a/src/browser/tests/css/external_stylesheet.html
+++ b/src/browser/tests/css/external_stylesheet.html
@@ -31,94 +31,102 @@
}
</script>
- <script id="ext_stylesheet_dynamic_load_event">
- {
+ <script id="ext_stylesheet_dynamic_load_event" type=module>
+ const state = await testing.async();
// Dynamically-inserted <link> fires `load` after the fetch completes.
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/styles/visibility.css';
- testing.async(async () => {
- const fired = await new Promise(resolve => {
- link.addEventListener('load', () => resolve(true));
- link.addEventListener('error', () => resolve(false));
- document.head.appendChild(link);
- });
+
+ const fired = await new Promise(resolve => {
+ link.addEventListener('load', () => resolve(true));
+ link.addEventListener('error', () => resolve(false));
+ document.head.appendChild(link);
+ });
+
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(true, fired);
});
- testing.expectEqual(true, true);
- }
</script>
- <script id="ext_stylesheet_404_fires_error">
- {
+ <script id="ext_stylesheet_404_fires_error" type=module>
+ const state = await testing.async();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/styles/404.css';
- testing.async(async () => {
- const evt = await new Promise(resolve => {
- link.addEventListener('load', () => resolve('load'));
- link.addEventListener('error', () => resolve('error'));
- document.head.appendChild(link);
- });
+
+ const evt = await new Promise(resolve => {
+ link.addEventListener('load', () => resolve('load'));
+ link.addEventListener('error', () => resolve('error'));
+ document.head.appendChild(link);
+ });
+
+ state.resolve();
+ await state.done(() => {
testing.expectEqual('error', evt);
});
- testing.expectEqual(true, true);
- }
</script>
- <script id="ext_stylesheet_oversize_fires_error">
- {
+ <script id="ext_stylesheet_oversize_fires_error" type=module>
+ const state = await testing.async();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/styles/oversize.css';
- testing.async(async () => {
- const evt = await new Promise(resolve => {
- link.addEventListener('load', () => resolve('load'));
- link.addEventListener('error', () => resolve('error'));
- document.head.appendChild(link);
- });
+
+ const evt = await new Promise(resolve => {
+ link.addEventListener('load', () => resolve('load'));
+ link.addEventListener('error', () => resolve('error'));
+ document.head.appendChild(link);
+ });
+
+ state.resolve();
+ await state.done(() => {
testing.expectEqual('error', evt);
});
- testing.expectEqual(true, true);
- }
</script>
- <script id="ext_stylesheet_href_change_replaces">
- {
+ <script id="ext_stylesheet_href_change_replaces" type=module>
// Mutating link.href on a connected stylesheet link must REPLACE the
// cached sheet's rules, not append a second entry to
// document.styleSheets. Regression test for the stale-sheet
// accumulation bug caught in code review.
+ const state = await testing.async();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/styles/visibility.css';
- testing.async(async () => {
- const baseline = document.styleSheets.length;
-
- await new Promise(resolve => {
- link.addEventListener('load', () => resolve(), { once: true });
- document.head.appendChild(link);
- });
- const afterFirst = document.styleSheets.length;
- testing.expectEqual(baseline + 1, afterFirst);
- const second = await new Promise(resolve => {
- link.addEventListener('load', () => resolve('load'), { once: true });
- link.addEventListener('error', () => resolve('error'), { once: true });
- link.href = '/styles/visibility2.css';
- });
+ const baseline = document.styleSheets.length;
+
+ await new Promise(resolve => {
+ link.addEventListener('load', () => resolve(), { once: true });
+ document.head.appendChild(link);
+ });
+ const afterFirst = document.styleSheets.length;
+
+ const second = await new Promise(resolve => {
+ link.addEventListener('load', () => resolve('load'), { once: true });
+ link.addEventListener('error', () => resolve('error'), { once: true });
+ link.href = '/styles/visibility2.css';
+ });
+ const afterSecond = document.styleSheets.length;
+
+ // New rules must be in effect after the swap. The reused sheet is
+ // the last registered one (the static head link registered first).
+ const sheet = document.styleSheets[afterFirst - 1];
+ const sheetHref = sheet.href;
+ const sheetRulesLen = sheet.cssRules.length;
+ const sheetSelector = sheet.cssRules[0].selectorText;
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(baseline + 1, afterFirst);
testing.expectEqual('load', second);
- testing.expectEqual(afterFirst, document.styleSheets.length);
-
- // New rules must be in effect after the swap. The reused sheet is
- // the last registered one (the static head link registered first).
- const sheet = document.styleSheets[afterFirst - 1];
- testing.expectEqual(testing.ORIGIN + '/styles/visibility2.css', sheet.href);
- testing.expectEqual(1, sheet.cssRules.length);
- testing.expectEqual('.ext-hide-2', sheet.cssRules[0].selectorText);
+ testing.expectEqual(afterFirst, afterSecond);
+ testing.expectEqual(testing.ORIGIN + '/styles/visibility2.css', sheetHref);
+ testing.expectEqual(1, sheetRulesLen);
+ testing.expectEqual('.ext-hide-2', sheetSelector);
});
- testing.expectEqual(true, true);
- }
</script>
<script id="ext_stylesheet_fragment_parse_skipped">
@@ -150,36 +158,40 @@
}
</script>
- <script id="ext_stylesheet_disconnect_removes">
- {
+ <script id="ext_stylesheet_disconnect_removes" type=module>
// Removing a connected stylesheet link must drop its sheet from
// document.styleSheets. Without symmetric deregistration the SPA
// theme-switch pattern (append new, remove old) would accumulate
// phantom entries and stale cascade rules.
+ const state = await testing.async();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/styles/visibility2.css';
- testing.async(async () => {
- const baseline = document.styleSheets.length;
-
- await new Promise(resolve => {
- link.addEventListener('load', () => resolve(), { once: true });
- document.head.appendChild(link);
- });
- testing.expectEqual(baseline + 1, document.styleSheets.length);
-
- link.remove();
- testing.expectEqual(baseline, document.styleSheets.length);
-
- // Re-appending must register fresh — the disconnect cleanup
- // cleared link._sheet so the cached short-circuit doesn't apply.
- await new Promise(resolve => {
- link.addEventListener('load', () => resolve(), { once: true });
- document.head.appendChild(link);
- });
- testing.expectEqual(baseline + 1, document.styleSheets.length);
+
+ const baseline = document.styleSheets.length;
+
+ await new Promise(resolve => {
+ link.addEventListener('load', () => resolve(), { once: true });
+ document.head.appendChild(link);
+ });
+ const afterAppend = document.styleSheets.length;
+
+ link.remove();
+ const afterRemove = document.styleSheets.length;
+
+ // Re-appending must register fresh — the disconnect cleanup
+ // cleared link._sheet so the cached short-circuit doesn't apply.
+ await new Promise(resolve => {
+ link.addEventListener('load', () => resolve(), { once: true });
+ document.head.appendChild(link);
+ });
+ const afterReappend = document.styleSheets.length;
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(baseline + 1, afterAppend);
+ testing.expectEqual(baseline, afterRemove);
+ testing.expectEqual(baseline + 1, afterReappend);
});
- testing.expectEqual(true, true);
- }
</script>
</body>
diff --git a/src/browser/tests/css/stylesheet.html b/src/browser/tests/css/stylesheet.html
index 0022050d8..a2bd7c896 100644
--- a/src/browser/tests/css/stylesheet.html
+++ b/src/browser/tests/css/stylesheet.html
@@ -520,26 +520,32 @@
}
</script>
-<script id="CSSStyleSheet_replaceSync">
-{
+<script id="CSSStyleSheet_replaceSync" type=module>
+ const state = await testing.async();
+
const sheet = new CSSStyleSheet();
- testing.expectEqual(0, sheet.cssRules.length);
+ const initialLen = sheet.cssRules.length;
sheet.replaceSync('.test { color: blue; }');
- testing.expectEqual(1, sheet.cssRules.length);
- testing.expectEqual('.test', sheet.cssRules[0].selectorText);
- testing.expectEqual('blue', sheet.cssRules[0].style.color);
+ const afterSyncLen = sheet.cssRules.length;
+ const afterSyncSelector = sheet.cssRules[0].selectorText;
+ const afterSyncColor = sheet.cssRules[0].style.color;
+
+ const result = await sheet.replace('.async-test { margin: 10px; }');
+ const afterAsyncLen = sheet.cssRules.length;
+ const afterAsyncSelector = sheet.cssRules[0].selectorText;
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(0, initialLen);
+ testing.expectEqual(1, afterSyncLen);
+ testing.expectEqual('.test', afterSyncSelector);
+ testing.expectEqual('blue', afterSyncColor);
- let replacedAsync = false;
- testing.async(async () => {
- const result = await sheet.replace('.async-test { margin: 10px; }');
testing.expectTrue(result === sheet);
- testing.expectEqual(1, sheet.cssRules.length);
- testing.expectEqual('.async-test', sheet.cssRules[0].selectorText);
- replacedAsync = true;
+ testing.expectEqual(1, afterAsyncLen);
+ testing.expectEqual('.async-test', afterAsyncSelector);
});
- testing.onload(() => testing.expectTrue(replacedAsync));
-}
</script>
<script id="CSSStyleRule_cssText">
diff --git a/src/browser/tests/element/html/event_listeners.html b/src/browser/tests/element/html/event_listeners.html
index 76db1a01a..616ebbe76 100644
--- a/src/browser/tests/element/html/event_listeners.html
+++ b/src/browser/tests/element/html/event_listeners.html
@@ -514,24 +514,16 @@
<img src="https://cdn.lightpanda.io/website/assets/images/docs/hn.png" />
-<script id="document-element-load">
-{
- let asyncBlockDispatched = false;
+<script id="document-element-load" type=module>
+ const state = await testing.async();
const docElement = document.documentElement;
- testing.async(async () => {
- const result = await new Promise(resolve => {
- // We should get this fired at capturing phase when a resource loaded.
- docElement.addEventListener("load", e => {
- testing.expectEqual(e.eventPhase, Event.CAPTURING_PHASE);
- return resolve(true);
- }, true);
- });
-
- asyncBlockDispatched = true;
- testing.expectEqual(true, result);
- });
+ // We should get this fired at capturing phase when a resource loaded.
+ docElement.addEventListener("load", e => {
+ state.resolve(e.eventPhase);
+ }, true);
- testing.onload(() => testing.expectEqual(true, asyncBlockDispatched));
-}
+ await state.done((eventPhase) => {
+ testing.expectEqual(Event.CAPTURING_PHASE, eventPhase);
+ });
</script>
diff --git a/src/browser/tests/element/html/image.html b/src/browser/tests/element/html/image.html
index 1e672a6ff..e9d918f05 100644
--- a/src/browser/tests/element/html/image.html
+++ b/src/browser/tests/element/html/image.html
@@ -118,29 +118,24 @@
<body></body>
-<script id="img-load-event">
-{
+<script id="img-load-event" type=module>
// An img fires a load event when src is set.
+ const state = await testing.async();
const img = document.createElement("img");
- let result = false;
- testing.async(async () => {
- await new Promise(resolve => {
- img.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
- testing.expectEqual(false, bubbles);
- testing.expectEqual(false, cancelBubble);
- testing.expectEqual(false, cancelable);
- testing.expectEqual(false, composed);
- testing.expectEqual(true, isTrusted);
- testing.expectEqual(img, target);
- result = true;
- return resolve();
- });
- img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
- });
+
+ img.addEventListener("load", (e) => {
+ state.resolve(e);
});
+ img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
- testing.onload(() => testing.expectEqual(true, result));
-}
+ await state.done((e) => {
+ testing.expectEqual(false, e.bubbles);
+ testing.expectEqual(false, e.cancelBubble);
+ testing.expectEqual(false, e.cancelable);
+ testing.expectEqual(false, e.composed);
+ testing.expectEqual(true, e.isTrusted);
+ testing.expectEqual(img, e.target);
+ });
</script>
<script id="img-no-load-without-src">
diff --git a/src/browser/tests/element/html/link.html b/src/browser/tests/element/html/link.html
index 754fe27e7..2831400b9 100644
--- a/src/browser/tests/element/html/link.html
+++ b/src/browser/tests/element/html/link.html
@@ -52,30 +52,26 @@
testing.expectEqual('print', l2.media);
</script>
-<script id="link-load-event">
-{
+<script id="link-load-event" type=module>
// A link with rel=stylesheet and a non-empty href fires a load event when appended to the DOM
+ const state = await testing.async();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://lightpanda.io/opensource-browser/15';
- testing.async(async () => {
- const result = await new Promise(resolve => {
- link.addEventListener('load', ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
- testing.expectEqual(false, bubbles);
- testing.expectEqual(false, cancelBubble);
- testing.expectEqual(false, cancelable);
- testing.expectEqual(false, composed);
- testing.expectEqual(true, isTrusted);
- testing.expectEqual(link, target);
- resolve(true);
- });
- document.head.appendChild(link);
- });
- testing.expectEqual(true, result);
+ link.addEventListener('load', (e) => {
+ state.resolve(e);
+ });
+ document.head.appendChild(link);
+
+ await state.done((e) => {
+ testing.expectEqual(false, e.bubbles);
+ testing.expectEqual(false, e.cancelBubble);
+ testing.expectEqual(false, e.cancelable);
+ testing.expectEqual(false, e.composed);
+ testing.expectEqual(true, e.isTrusted);
+ testing.expectEqual(link, e.target);
});
- testing.expectEqual(true, true);
-}
</script>
<script id="link-no-load-without-href">
diff --git a/src/browser/tests/element/html/style.html b/src/browser/tests/element/html/style.html
index 45aeed4e4..2f91a9d6a 100644
--- a/src/browser/tests/element/html/style.html
+++ b/src/browser/tests/element/html/style.html
@@ -107,29 +107,24 @@
}
</script>
-<script id="style-load-event">
-{
+<script id="style-load-event" type=module>
// A style element fires a load event when appended to the DOM.
+ const state = await testing.async();
const style = document.createElement("style");
- let result = false;
- testing.async(async () => {
- await new Promise(resolve => {
- style.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
- testing.expectEqual(false, bubbles);
- testing.expectEqual(false, cancelBubble);
- testing.expectEqual(false, cancelable);
- testing.expectEqual(false, composed);
- testing.expectEqual(true, isTrusted);
- testing.expectEqual(style, target);
- result = true;
- return resolve();
- });
- document.head.appendChild(style);
- });
+
+ style.addEventListener("load", (e) => {
+ state.resolve(e);
});
+ document.head.appendChild(style);
- testing.onload(() => testing.expectEqual(true, result));
-}
+ await state.done((e) => {
+ testing.expectEqual(false, e.bubbles);
+ testing.expectEqual(false, e.cancelBubble);
+ testing.expectEqual(false, e.cancelable);
+ testing.expectEqual(false, e.composed);
+ testing.expectEqual(true, e.isTrusted);
+ testing.expectEqual(style, e.target);
+ });
</script>
<script id="style-tag-content-parsing">
diff --git a/src/browser/tests/file_reader.html b/src/browser/tests/file_reader.html
index ca0d87c4a..6176668fe 100644
--- a/src/browser/tests/file_reader.html
+++ b/src/browser/tests/file_reader.html
@@ -16,120 +16,122 @@
testing.expectEqual(2, FileReader.DONE);
</script>
-<script id=readAsText>
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob(["Hello, World!"], { type: "text/plain" });
-
- let loadstartFired = false;
- let progressFired = false;
- let loadFired = false;
- let loadendFired = false;
-
- const promise = new Promise((resolve) => {
- reader.onloadstart = function(e) {
- loadstartFired = true;
- testing.expectEqual("loadstart", e.type);
- testing.expectEqual(1, reader.readyState);
- };
-
- reader.onprogress = function(e) {
- progressFired = true;
- testing.expectEqual(13, e.loaded);
- testing.expectEqual(13, e.total);
- };
-
- reader.onload = function(e) {
- loadFired = true;
- testing.expectEqual(2, reader.readyState);
- testing.expectEqual("Hello, World!", reader.result);
- };
-
- reader.onloadend = function(e) {
- loadendFired = true;
- testing.expectEqual(true, loadstartFired);
- testing.expectEqual(true, progressFired);
- testing.expectEqual(true, loadFired);
- resolve();
- };
- });
+<script id=readAsText type=module>
+ const state = await testing.async();
+ const reader = new FileReader();
+ const blob = new Blob(["Hello, World!"], { type: "text/plain" });
+
+ let loadstartFired = false;
+ let progressFired = false;
+ let loadFired = false;
+ let loadendFired = false;
+
+ let loadstartType = null;
+ let loadstartReadyState = null;
+ let progressLoaded = null;
+ let progressTotal = null;
+ let loadReadyState = null;
+ let loadResult = null;
+
+ reader.onloadstart = function(e) {
+ loadstartFired = true;
+ loadstartType = e.type;
+ loadstartReadyState = reader.readyState;
+ };
+
+ reader.onprogress = function(e) {
+ progressFired = true;
+ progressLoaded = e.loaded;
+ progressTotal = e.total;
+ };
+
+ reader.onload = function(e) {
+ loadFired = true;
+ loadReadyState = reader.readyState;
+ loadResult = reader.result;
+ };
+
+ reader.onloadend = function(e) {
+ loadendFired = true;
+ state.resolve();
+ };
+
+ reader.readAsText(blob);
+
+ await state.done(() => {
+ testing.expectEqual(true, loadstartFired);
+ testing.expectEqual("loadstart", loadstartType);
+ testing.expectEqual(1, loadstartReadyState);
+
+ testing.expectEqual(true, progressFired);
+ testing.expectEqual(13, progressLoaded);
+ testing.expectEqual(13, progressTotal);
- reader.readAsText(blob);
- await promise;
+ testing.expectEqual(true, loadFired);
+ testing.expectEqual(2, loadReadyState);
+ testing.expectEqual("Hello, World!", loadResult);
+
+ testing.expectEqual(true, loadendFired);
});
</script>
-<script id=readAsDataURL>
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob(["test"], { type: "text/plain" });
-
- const promise = new Promise((resolve) => {
- reader.onload = function() {
- testing.expectEqual("data:text/plain;base64,dGVzdA==", reader.result);
- resolve();
- };
- });
+<script id=readAsDataURL type=module>
+ const state = await testing.async();
- reader.readAsDataURL(blob);
- await promise;
+ const reader1 = new FileReader();
+ const blob1 = new Blob(["test"], { type: "text/plain" });
+ const result1 = await new Promise((resolve) => {
+ reader1.onload = function() { resolve(reader1.result); };
+ reader1.readAsDataURL(blob1);
});
// Empty MIME type
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob(["test"]);
-
- const promise = new Promise((resolve) => {
- reader.onload = function() {
- testing.expectEqual("data:application/octet-stream;base64,dGVzdA==", reader.result);
- resolve();
- };
- });
+ const reader2 = new FileReader();
+ const blob2 = new Blob(["test"]);
+ const result2 = await new Promise((resolve) => {
+ reader2.onload = function() { resolve(reader2.result); };
+ reader2.readAsDataURL(blob2);
+ });
- reader.readAsDataURL(blob);
- await promise;
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("data:text/plain;base64,dGVzdA==", result1);
+ testing.expectEqual("data:application/octet-stream;base64,dGVzdA==", result2);
});
</script>
-<script id=readAsArrayBuffer>
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob([new Uint8Array([65, 66, 67])]);
-
- const promise = new Promise((resolve) => {
- reader.onload = function() {
- const result = reader.result;
- testing.expectEqual(true, result instanceof ArrayBuffer);
- testing.expectEqual(3, result.byteLength);
-
- const view = new Uint8Array(result);
- testing.expectEqual(65, view[0]);
- testing.expectEqual(66, view[1]);
- testing.expectEqual(67, view[2]);
- resolve();
- };
- });
-
+<script id=readAsArrayBuffer type=module>
+ const state = await testing.async();
+ const reader = new FileReader();
+ const blob = new Blob([new Uint8Array([65, 66, 67])]);
+ const result = await new Promise((resolve) => {
+ reader.onload = function() { resolve(reader.result); };
reader.readAsArrayBuffer(blob);
- await promise;
+ });
+ const view = new Uint8Array(result);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, result instanceof ArrayBuffer);
+ testing.expectEqual(3, result.byteLength);
+ testing.expectEqual(65, view[0]);
+ testing.expectEqual(66, view[1]);
+ testing.expectEqual(67, view[2]);
});
</script>
-<script id=readAsBinaryString>
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob(["ABC"]);
-
- const promise = new Promise((resolve) => {
- reader.onload = function() {
- testing.expectEqual("ABC", reader.result);
- resolve();
- };
- });
-
+<script id=readAsBinaryString type=module>
+ const state = await testing.async();
+ const reader = new FileReader();
+ const blob = new Blob(["ABC"]);
+ const result = await new Promise((resolve) => {
+ reader.onload = function() { resolve(reader.result); };
reader.readAsBinaryString(blob);
- await promise;
+ });
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("ABC", result);
});
</script>
@@ -147,51 +149,49 @@
// We test that abort() at least doesn't throw and maintains correct state.
</script>
-<script id=multipleReads>
- testing.async(async () => {
- const reader = new FileReader();
- const blob1 = new Blob(["first"]);
- const blob2 = new Blob(["second"]);
-
- // First read
- const promise1 = new Promise((resolve) => {
- reader.onload = function() {
- testing.expectEqual("first", reader.result);
- resolve();
- };
- });
+<script id=multipleReads type=module>
+ const state = await testing.async();
+ const reader = new FileReader();
+ const blob1 = new Blob(["first"]);
+ const blob2 = new Blob(["second"]);
+
+ // First read
+ const result1 = await new Promise((resolve) => {
+ reader.onload = function() { resolve(reader.result); };
reader.readAsText(blob1);
- await promise1;
-
- // Second read - should work after first completes
- const promise2 = new Promise((resolve) => {
- reader.onload = function() {
- testing.expectEqual("second", reader.result);
- resolve();
- };
- });
+ });
+
+ // Second read - should work after first completes
+ const result2 = await new Promise((resolve) => {
+ reader.onload = function() { resolve(reader.result); };
reader.readAsText(blob2);
- await promise2;
});
-</script>
-<script id=addEventListener>
- testing.async(async () => {
- const reader = new FileReader();
- const blob = new Blob(["test"]);
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("first", result1);
+ testing.expectEqual("second", result2);
+ });
+</script>
- let loadFired = false;
+<script id=addEventListener type=module>
+ const state = await testing.async();
+ const reader = new FileReader();
+ const blob = new Blob(["test"]);
- const promise = new Promise((resolve) => {
- reader.addEventListener("load", function() {
- loadFired = true;
- resolve();
- });
+ let loadFired = false;
+ await new Promise((resolve) => {
+ reader.addEventListener("load", function() {
+ loadFired = true;
+ resolve();
});
-
reader.readAsText(blob);
- await promise;
+ });
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(true, loadFired);
});
</script>
+</content>
+</invoke>
diff --git a/src/browser/tests/message_channel.html b/src/browser/tests/message_channel.html
index 0a9848f78..65df1c986 100644
--- a/src/browser/tests/message_channel.html
+++ b/src/browser/tests/message_channel.html
@@ -1,86 +1,71 @@
<!DOCTYPE html>
<body>
<script src="testing.js"></script>
-<script id="basic">
-{
- const channel = new MessageChannel();
+<script id="basic" type=module>
+ const state = await testing.async();
+
+ // ports are distinct and defined
+ const channel0 = new MessageChannel();
+
+ // single message delivered to port2
+ const channel1 = new MessageChannel();
+ let received1 = null;
+ channel1.port2.onmessage = function(e) {
+ received1 = e.data;
+ };
+ channel1.port1.postMessage('hello');
+
+ // addEventListener + start() preserves message order
+ let messages = [];
+ const channel2 = new MessageChannel();
+ channel2.port2.addEventListener('message', (e) => {
+ messages.push(e.data);
+ });
+ channel2.port2.start();
+ channel2.port1.postMessage('first');
+ channel2.port1.postMessage('second');
+ channel2.port1.postMessage('third');
+
+ // bidirectional delivery, one message each way
+ const channel3 = new MessageChannel();
+ let port1Count = 0;
+ let port2Count = 0;
+ channel3.port1.onmessage = () => { port1Count++; };
+ channel3.port2.onmessage = () => { port2Count++; };
+ channel3.port1.postMessage('to port2');
+ channel3.port2.postMessage('to port1');
+
+ // structured object message
+ const channel4 = new MessageChannel();
+ let received4 = null;
+ channel4.port2.onmessage = (e) => {
+ received4 = e.data;
+ };
+ channel4.port1.postMessage({ type: 'test', value: 42 });
+
+ // let all queued messages be delivered
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, channel0.port1 !== undefined);
+ testing.expectEqual(true, channel0.port2 !== undefined);
+ testing.expectEqual(true, channel0.port1 !== channel0.port2);
+
+ testing.expectEqual('hello', received1);
- testing.expectEqual(true, channel.port1 !== undefined);
- testing.expectEqual(true, channel.port2 !== undefined);
- testing.expectEqual(true, channel.port1 !== channel.port2);
-}
-
-{
- const channel = new MessageChannel();
- let received = null;
-
- channel.port2.onmessage = function(e) {
- received = e.data;
- };
-
- channel.port1.postMessage('hello');
-
- setTimeout(() => {
- testing.expectEqual('hello', received);
- }, 10);
-}
-
-testing.async(async () => {
- let messages = [];
-
- let p = new Promise((resolve) => {
- const channel = new MessageChannel();
- channel.port2.addEventListener('message', (e) => {
- messages.push(e.data);
- if (e.data === 'third') {
- resolve();
- }
- });
- channel.port2.start();
-
- channel.port1.postMessage('first');
- channel.port1.postMessage('second');
- channel.port1.postMessage('third');
- });
-
-
- await p;
testing.expectEqual(3, messages.length);
testing.expectEqual('first', messages[0]);
testing.expectEqual('second', messages[1]);
testing.expectEqual('third', messages[2]);
-});
-
-{
- const channel = new MessageChannel();
- let port1Count = 0;
- let port2Count = 0;
-
- channel.port1.onmessage = () => { port1Count++; };
- channel.port2.onmessage = () => { port2Count++; };
-
- channel.port1.postMessage('to port2');
- channel.port2.postMessage('to port1');
-
- setTimeout(() => {
- testing.expectEqual(1, port1Count);
- testing.expectEqual(1, port2Count);
- }, 30);
-}
-
-{
- const channel = new MessageChannel();
- let received = null;
-
- channel.port2.onmessage = (e) => {
- received = e.data;
- };
- channel.port1.postMessage({ type: 'test', value: 42 });
+ testing.expectEqual(1, port1Count);
+ testing.expectEqual(1, port2Count);
- setTimeout(() => {
- testing.expectEqual('test', received.type);
- testing.expectEqual(42, received.value);
- }, 40);
-}
+ testing.expectEqual('test', received4.type);
+ testing.expectEqual(42, received4.value);
+ });
</script>
+</body>
+</content>
+</invoke>
diff --git a/src/browser/tests/mutation_observer/attribute_filter.html b/src/browser/tests/mutation_observer/attribute_filter.html
index eb1c0605f..72395aa55 100644
--- a/src/browser/tests/mutation_observer/attribute_filter.html
+++ b/src/browser/tests/mutation_observer/attribute_filter.html
@@ -6,152 +6,146 @@
</div>
<script src="../testing.js"></script>
-<script id="attribute_filter_single">
- testing.async(async () => {
- const element = document.getElementById('test-element-1');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(element, {
- attributes: true,
- attributeFilter: ['data-status']
- });
-
- element.setAttribute('data-status', 'inactive');
- element.setAttribute('data-username', 'jane');
- element.setAttribute('data-role', 'user');
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('attributes', mutations[0].type);
- testing.expectEqual('data-status', mutations[0].attributeName);
- });
+<script id="attribute_filter_single" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-1');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(element, {
+ attributes: true,
+ attributeFilter: ['data-status']
+ });
+
+ element.setAttribute('data-status', 'inactive');
+ element.setAttribute('data-username', 'jane');
+ element.setAttribute('data-role', 'user');
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('attributes', mutations[0].type);
+ testing.expectEqual('data-status', mutations[0].attributeName);
});
</script>
-<script id="attribute_filter_multiple">
- testing.async(async () => {
- const element = document.getElementById('test-element-1');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(element, {
- attributes: true,
- attributeFilter: ['data-status', 'data-username']
- });
-
- element.setAttribute('data-status', 'active');
- element.setAttribute('data-username', 'alice');
- element.setAttribute('data-role', 'moderator');
-
- Promise.resolve().then(() => {
- testing.expectEqual(2, mutations.length);
- testing.expectEqual('data-status', mutations[0].attributeName);
- testing.expectEqual('data-username', mutations[1].attributeName);
- });
+<script id="attribute_filter_multiple" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-1');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(element, {
+ attributes: true,
+ attributeFilter: ['data-status', 'data-username']
+ });
+
+ element.setAttribute('data-status', 'active');
+ element.setAttribute('data-username', 'alice');
+ element.setAttribute('data-role', 'moderator');
+
+ await state.done((mutations) => {
+ testing.expectEqual(2, mutations.length);
+ testing.expectEqual('data-status', mutations[0].attributeName);
+ testing.expectEqual('data-username', mutations[1].attributeName);
});
</script>
-<script id="attribute_filter_with_old_value">
- testing.async(async () => {
- const element = document.getElementById('test-element-2');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(element, {
- attributes: true,
- attributeOldValue: true,
- attributeFilter: ['class']
- });
-
- element.setAttribute('class', 'changed');
- element.setAttribute('data-ignored', 'value');
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('class', mutations[0].attributeName);
- testing.expectEqual('initial', mutations[0].oldValue);
- });
+<script id="attribute_filter_with_old_value" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-2');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(element, {
+ attributes: true,
+ attributeOldValue: true,
+ attributeFilter: ['class']
+ });
+
+ element.setAttribute('class', 'changed');
+ element.setAttribute('data-ignored', 'value');
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('class', mutations[0].attributeName);
+ testing.expectEqual('initial', mutations[0].oldValue);
});
</script>
-<script id="attribute_filter_no_match">
- testing.async(async () => {
- const element = document.getElementById('test-element-2');
+<script id="attribute_filter_no_match" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-2');
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
- observer.observe(element, {
- attributes: true,
- attributeFilter: ['data-filtered']
- });
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
+ observer.observe(element, {
+ attributes: true,
+ attributeFilter: ['data-filtered']
+ });
- element.setAttribute('class', 'another-change');
- element.setAttribute('data-other', 'value');
+ element.setAttribute('class', 'another-change');
+ element.setAttribute('data-other', 'value');
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- observer.disconnect();
- });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ observer.disconnect();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(false, callbackCalled);
});
</script>
-<script id="attribute_filter_with_subtree">
- testing.async(async () => {
- const parent = document.getElementById('test-element-3');
- const child = document.getElementById('child-element');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(parent, {
- attributes: true,
- subtree: true,
- attributeFilter: ['data-foo']
- });
-
- child.setAttribute('data-foo', 'changed');
- child.setAttribute('data-baz', 'ignored');
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('data-foo', mutations[0].attributeName);
- testing.expectEqual(child, mutations[0].target);
- });
+<script id="attribute_filter_with_subtree" type=module>
+ const state = await testing.async();
+ const parent = document.getElementById('test-element-3');
+ const child = document.getElementById('child-element');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(parent, {
+ attributes: true,
+ subtree: true,
+ attributeFilter: ['data-foo']
+ });
+
+ child.setAttribute('data-foo', 'changed');
+ child.setAttribute('data-baz', 'ignored');
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('data-foo', mutations[0].attributeName);
+ testing.expectEqual(child, mutations[0].target);
});
</script>
-<script id="attribute_filter_empty_array">
- testing.async(async () => {
- const element = document.getElementById('test-element-2');
-
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
- observer.observe(element, {
- attributes: true,
- attributeFilter: []
- });
-
- element.setAttribute('class', 'yet-another-change');
-
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- observer.disconnect();
- });
+<script id="attribute_filter_empty_array" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-2');
+
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
+ observer.observe(element, {
+ attributes: true,
+ attributeFilter: []
+ });
+
+ element.setAttribute('class', 'yet-another-change');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ observer.disconnect();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(false, callbackCalled);
});
</script>
diff --git a/src/browser/tests/mutation_observer/character_data.html b/src/browser/tests/mutation_observer/character_data.html
index 260d28228..1fd68f379 100644
--- a/src/browser/tests/mutation_observer/character_data.html
+++ b/src/browser/tests/mutation_observer/character_data.html
@@ -4,76 +4,73 @@
<div id="test-element-3">Test</div>
<script src="../testing.js"></script>
-<script id="character_data">
- testing.async(async () => {
- const element = document.getElementById('test-element-1');
- const textNode = element.firstChild;
+<script id="character_data" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-1');
+ const textNode = element.firstChild;
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(textNode, { characterData: true });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(textNode, { characterData: true });
- textNode.data = 'Changed text';
+ textNode.data = 'Changed text';
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('characterData', mutations[0].type);
- testing.expectEqual(textNode, mutations[0].target);
- testing.expectEqual(null, mutations[0].oldValue);
- });
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('characterData', mutations[0].type);
+ testing.expectEqual(textNode, mutations[0].target);
+ testing.expectEqual(null, mutations[0].oldValue);
});
</script>
-<script id="character_data_old_value">
- testing.async(async () => {
- const element = document.getElementById('test-element-2');
- const textNode = element.firstChild;
+<script id="character_data_old_value" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-2');
+ const textNode = element.firstChild;
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(textNode, { characterData: true, characterDataOldValue: true });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(textNode, { characterData: true, characterDataOldValue: true });
- textNode.data = 'First change';
- textNode.data = 'Second change';
+ textNode.data = 'First change';
+ textNode.data = 'Second change';
- Promise.resolve().then(() => {
- testing.expectEqual(2, mutations.length);
+ await state.done((mutations) => {
+ testing.expectEqual(2, mutations.length);
- testing.expectEqual('characterData', mutations[0].type);
- testing.expectEqual(textNode, mutations[0].target);
- testing.expectEqual('Test', mutations[0].oldValue);
+ testing.expectEqual('characterData', mutations[0].type);
+ testing.expectEqual(textNode, mutations[0].target);
+ testing.expectEqual('Test', mutations[0].oldValue);
- testing.expectEqual('characterData', mutations[1].type);
- testing.expectEqual(textNode, mutations[1].target);
- testing.expectEqual('First change', mutations[1].oldValue);
- });
+ testing.expectEqual('characterData', mutations[1].type);
+ testing.expectEqual(textNode, mutations[1].target);
+ testing.expectEqual('First change', mutations[1].oldValue);
});
</script>
-<script id="character_data_no_observe">
- testing.async(async () => {
- const element = document.getElementById('test-element-3');
- const textNode = element.firstChild;
+<script id="character_data_no_observe" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-3');
+ const textNode = element.firstChild;
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
- // Observe for attributes, not characterData
- observer.observe(element, { attributes: true });
+ // Observe for attributes, not characterData
+ observer.observe(element, { attributes: true });
- // Change text node data (should not trigger)
- textNode.data = 'Changed but not observed';
+ // Change text node data (should not trigger)
+ textNode.data = 'Changed but not observed';
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(false, callbackCalled);
});
</script>
diff --git a/src/browser/tests/mutation_observer/childlist.html b/src/browser/tests/mutation_observer/childlist.html
index e15eaa35a..77decbe08 100644
--- a/src/browser/tests/mutation_observer/childlist.html
+++ b/src/browser/tests/mutation_observer/childlist.html
@@ -6,322 +6,304 @@
<div id="middle-parent"><div id="first">First</div><div id="middle">Middle</div><div id="last">Last</div></div>
<script src="../testing.js"></script>
-<script id="childlist">
- testing.async(async () => {
- const parent = document.getElementById('parent');
- const child1 = document.getElementById('child1');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(parent, { childList: true });
-
- const child2 = document.createElement('div');
- child2.textContent = 'Child 2';
- parent.appendChild(child2);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(parent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(child2, mutations[0].addedNodes[0]);
- testing.expectEqual(0, mutations[0].removedNodes.length);
- testing.expectEqual(child1, mutations[0].previousSibling);
- testing.expectEqual(null, mutations[0].nextSibling);
- });
+<script id="childlist" type=module>
+ const state = await testing.async();
+ const parent = document.getElementById('parent');
+ const child1 = document.getElementById('child1');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(parent, { childList: true });
+
+ const child2 = document.createElement('div');
+ child2.textContent = 'Child 2';
+ parent.appendChild(child2);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(parent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(child2, mutations[0].addedNodes[0]);
+ testing.expectEqual(0, mutations[0].removedNodes.length);
+ testing.expectEqual(child1, mutations[0].previousSibling);
+ testing.expectEqual(null, mutations[0].nextSibling);
});
</script>
-<script id="childlist_empty_parent">
- testing.async(async () => {
- const emptyParent = document.getElementById('empty-parent');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(emptyParent, { childList: true });
-
- const firstChild = document.createElement('div');
- firstChild.textContent = 'First child';
- emptyParent.appendChild(firstChild);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(emptyParent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(firstChild, mutations[0].addedNodes[0]);
- testing.expectEqual(0, mutations[0].removedNodes.length);
- testing.expectEqual(null, mutations[0].previousSibling);
- testing.expectEqual(null, mutations[0].nextSibling);
- });
+<script id="childlist_empty_parent" type=module>
+ const state = await testing.async();
+ const emptyParent = document.getElementById('empty-parent');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(emptyParent, { childList: true });
+
+ const firstChild = document.createElement('div');
+ firstChild.textContent = 'First child';
+ emptyParent.appendChild(firstChild);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(emptyParent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(firstChild, mutations[0].addedNodes[0]);
+ testing.expectEqual(0, mutations[0].removedNodes.length);
+ testing.expectEqual(null, mutations[0].previousSibling);
+ testing.expectEqual(null, mutations[0].nextSibling);
});
</script>
-<script id="childlist_remove_last">
- testing.async(async () => {
- const removeParent = document.getElementById('remove-parent');
- const onlyChild = document.getElementById('only-child');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(removeParent, { childList: true });
-
- removeParent.removeChild(onlyChild);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(removeParent, mutations[0].target);
- testing.expectEqual(0, mutations[0].addedNodes.length);
- testing.expectEqual(1, mutations[0].removedNodes.length);
- testing.expectEqual(onlyChild, mutations[0].removedNodes[0]);
- testing.expectEqual(null, mutations[0].previousSibling);
- testing.expectEqual(null, mutations[0].nextSibling);
- });
+<script id="childlist_remove_last" type=module>
+ const state = await testing.async();
+ const removeParent = document.getElementById('remove-parent');
+ const onlyChild = document.getElementById('only-child');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(removeParent, { childList: true });
+
+ removeParent.removeChild(onlyChild);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(removeParent, mutations[0].target);
+ testing.expectEqual(0, mutations[0].addedNodes.length);
+ testing.expectEqual(1, mutations[0].removedNodes.length);
+ testing.expectEqual(onlyChild, mutations[0].removedNodes[0]);
+ testing.expectEqual(null, mutations[0].previousSibling);
+ testing.expectEqual(null, mutations[0].nextSibling);
});
</script>
-<script id="childlist_text_node">
- testing.async(async () => {
- const textParent = document.getElementById('text-parent');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(textParent, { childList: true });
-
- const textNode = document.createTextNode('Hello world');
- textParent.appendChild(textNode);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(textParent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(textNode, mutations[0].addedNodes[0]);
- testing.expectEqual(null, mutations[0].previousSibling);
- testing.expectEqual(null, mutations[0].nextSibling);
- });
+<script id="childlist_text_node" type=module>
+ const state = await testing.async();
+ const textParent = document.getElementById('text-parent');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(textParent, { childList: true });
+
+ const textNode = document.createTextNode('Hello world');
+ textParent.appendChild(textNode);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(textParent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(textNode, mutations[0].addedNodes[0]);
+ testing.expectEqual(null, mutations[0].previousSibling);
+ testing.expectEqual(null, mutations[0].nextSibling);
});
</script>
-<script id="childlist_remove_middle">
- testing.async(async () => {
- const middleParent = document.getElementById('middle-parent');
- const first = document.getElementById('first');
- const middle = document.getElementById('middle');
- const last = document.getElementById('last');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(middleParent, { childList: true });
-
- middleParent.removeChild(middle);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(middleParent, mutations[0].target);
- testing.expectEqual(0, mutations[0].addedNodes.length);
- testing.expectEqual(1, mutations[0].removedNodes.length);
- testing.expectEqual(middle, mutations[0].removedNodes[0]);
- testing.expectEqual(first, mutations[0].previousSibling);
- testing.expectEqual(last, mutations[0].nextSibling);
- });
+<script id="childlist_remove_middle" type=module>
+ const state = await testing.async();
+ const middleParent = document.getElementById('middle-parent');
+ const first = document.getElementById('first');
+ const middle = document.getElementById('middle');
+ const last = document.getElementById('last');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(middleParent, { childList: true });
+
+ middleParent.removeChild(middle);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(middleParent, mutations[0].target);
+ testing.expectEqual(0, mutations[0].addedNodes.length);
+ testing.expectEqual(1, mutations[0].removedNodes.length);
+ testing.expectEqual(middle, mutations[0].removedNodes[0]);
+ testing.expectEqual(first, mutations[0].previousSibling);
+ testing.expectEqual(last, mutations[0].nextSibling);
});
</script>
<div id="insert-parent"><div id="insert-first">First</div><div id="insert-last">Last</div></div>
-<script id="childlist_insert_before">
- testing.async(async () => {
- const insertParent = document.getElementById('insert-parent');
- const insertFirst = document.getElementById('insert-first');
- const insertLast = document.getElementById('insert-last');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(insertParent, { childList: true });
-
- const insertMiddle = document.createElement('div');
- insertMiddle.textContent = 'Middle';
- insertParent.insertBefore(insertMiddle, insertLast);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(insertParent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(insertMiddle, mutations[0].addedNodes[0]);
- testing.expectEqual(0, mutations[0].removedNodes.length);
- testing.expectEqual(insertFirst, mutations[0].previousSibling);
- testing.expectEqual(insertLast, mutations[0].nextSibling);
- });
+<script id="childlist_insert_before" type=module>
+ const state = await testing.async();
+ const insertParent = document.getElementById('insert-parent');
+ const insertFirst = document.getElementById('insert-first');
+ const insertLast = document.getElementById('insert-last');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(insertParent, { childList: true });
+
+ const insertMiddle = document.createElement('div');
+ insertMiddle.textContent = 'Middle';
+ insertParent.insertBefore(insertMiddle, insertLast);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(insertParent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(insertMiddle, mutations[0].addedNodes[0]);
+ testing.expectEqual(0, mutations[0].removedNodes.length);
+ testing.expectEqual(insertFirst, mutations[0].previousSibling);
+ testing.expectEqual(insertLast, mutations[0].nextSibling);
});
</script>
<div id="replace-parent"><div id="replace-old">Old</div></div>
-<script id="childlist_replace_child">
- testing.async(async () => {
- const replaceParent = document.getElementById('replace-parent');
- const replaceOld = document.getElementById('replace-old');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(replaceParent, { childList: true });
-
- const replaceNew = document.createElement('div');
- replaceNew.textContent = 'New';
- replaceParent.replaceChild(replaceNew, replaceOld);
-
- Promise.resolve().then(() => {
- // replaceChild generates two separate mutation records in modern spec:
- // 1. First record for insertBefore (new node added)
- // 2. Second record for removeChild (old node removed)
- testing.expectEqual(2, mutations.length);
-
- // First mutation: insertion of new node
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(replaceParent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(replaceNew, mutations[0].addedNodes[0]);
- testing.expectEqual(0, mutations[0].removedNodes.length);
- testing.expectEqual(null, mutations[0].previousSibling);
- testing.expectEqual(replaceOld, mutations[0].nextSibling);
-
- // Second mutation: removal of old node
- testing.expectEqual('childList', mutations[1].type);
- testing.expectEqual(replaceParent, mutations[1].target);
- testing.expectEqual(0, mutations[1].addedNodes.length);
- testing.expectEqual(1, mutations[1].removedNodes.length);
- testing.expectEqual(replaceOld, mutations[1].removedNodes[0]);
- testing.expectEqual(replaceNew, mutations[1].previousSibling);
- testing.expectEqual(null, mutations[1].nextSibling);
- });
+<script id="childlist_replace_child" type=module>
+ const state = await testing.async();
+ const replaceParent = document.getElementById('replace-parent');
+ const replaceOld = document.getElementById('replace-old');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(replaceParent, { childList: true });
+
+ const replaceNew = document.createElement('div');
+ replaceNew.textContent = 'New';
+ replaceParent.replaceChild(replaceNew, replaceOld);
+
+ await state.done((mutations) => {
+ // replaceChild generates two separate mutation records in modern spec:
+ // 1. First record for insertBefore (new node added)
+ // 2. Second record for removeChild (old node removed)
+ testing.expectEqual(2, mutations.length);
+
+ // First mutation: insertion of new node
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(replaceParent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(replaceNew, mutations[0].addedNodes[0]);
+ testing.expectEqual(0, mutations[0].removedNodes.length);
+ testing.expectEqual(null, mutations[0].previousSibling);
+ testing.expectEqual(replaceOld, mutations[0].nextSibling);
+
+ // Second mutation: removal of old node
+ testing.expectEqual('childList', mutations[1].type);
+ testing.expectEqual(replaceParent, mutations[1].target);
+ testing.expectEqual(0, mutations[1].addedNodes.length);
+ testing.expectEqual(1, mutations[1].removedNodes.length);
+ testing.expectEqual(replaceOld, mutations[1].removedNodes[0]);
+ testing.expectEqual(replaceNew, mutations[1].previousSibling);
+ testing.expectEqual(null, mutations[1].nextSibling);
});
</script>
<div id="multiple-parent"></div>
-<script id="childlist_multiple_mutations">
- testing.async(async () => {
- const multipleParent = document.getElementById('multiple-parent');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(multipleParent, { childList: true });
-
- const child1 = document.createElement('div');
- child1.textContent = 'Child 1';
- multipleParent.appendChild(child1);
-
- const child2 = document.createElement('div');
- child2.textContent = 'Child 2';
- multipleParent.appendChild(child2);
-
- const child3 = document.createElement('div');
- child3.textContent = 'Child 3';
- multipleParent.appendChild(child3);
-
- Promise.resolve().then(() => {
- testing.expectEqual(3, mutations.length);
-
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(child1, mutations[0].addedNodes[0]);
- testing.expectEqual(null, mutations[0].previousSibling);
- testing.expectEqual(null, mutations[0].nextSibling);
-
- testing.expectEqual('childList', mutations[1].type);
- testing.expectEqual(child2, mutations[1].addedNodes[0]);
- testing.expectEqual(child1, mutations[1].previousSibling);
- testing.expectEqual(null, mutations[1].nextSibling);
-
- testing.expectEqual('childList', mutations[2].type);
- testing.expectEqual(child3, mutations[2].addedNodes[0]);
- testing.expectEqual(child2, mutations[2].previousSibling);
- testing.expectEqual(null, mutations[2].nextSibling);
- });
+<script id="childlist_multiple_mutations" type=module>
+ const state = await testing.async();
+ const multipleParent = document.getElementById('multiple-parent');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(multipleParent, { childList: true });
+
+ const child1 = document.createElement('div');
+ child1.textContent = 'Child 1';
+ multipleParent.appendChild(child1);
+
+ const child2 = document.createElement('div');
+ child2.textContent = 'Child 2';
+ multipleParent.appendChild(child2);
+
+ const child3 = document.createElement('div');
+ child3.textContent = 'Child 3';
+ multipleParent.appendChild(child3);
+
+ await state.done((mutations) => {
+ testing.expectEqual(3, mutations.length);
+
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(child1, mutations[0].addedNodes[0]);
+ testing.expectEqual(null, mutations[0].previousSibling);
+ testing.expectEqual(null, mutations[0].nextSibling);
+
+ testing.expectEqual('childList', mutations[1].type);
+ testing.expectEqual(child2, mutations[1].addedNodes[0]);
+ testing.expectEqual(child1, mutations[1].previousSibling);
+ testing.expectEqual(null, mutations[1].nextSibling);
+
+ testing.expectEqual('childList', mutations[2].type);
+ testing.expectEqual(child3, mutations[2].addedNodes[0]);
+ testing.expectEqual(child2, mutations[2].previousSibling);
+ testing.expectEqual(null, mutations[2].nextSibling);
});
</script>
<div id="inner-html-parent"><div>Old 1</div><div>Old 2</div><div>Old 3</div></div>
-<script id="childlist_inner_html">
- testing.async(async () => {
- const innerHtmlParent = document.getElementById('inner-html-parent');
- const oldChildren = Array.from(innerHtmlParent.children);
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(innerHtmlParent, { childList: true });
-
- // No whitespace between tags to avoid text node mutations
- innerHtmlParent.innerHTML = '<span>New 1</span><span>New 2</span><span>New 3</span>';
-
- Promise.resolve().then(() => {
- // innerHTML triggers mutations for both removals and additions
- // With tri-state: from_parser=true + parse_mode=fragment -> mutations fire
- // HTML wrapper element is filtered out, so: 3 removals + 3 additions = 6
- testing.expectEqual(6, mutations.length);
-
- // First 3: removals
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(1, mutations[0].removedNodes.length);
- testing.expectEqual(oldChildren[0], mutations[0].removedNodes[0]);
- testing.expectEqual(0, mutations[0].addedNodes.length);
-
- testing.expectEqual('childList', mutations[1].type);
- testing.expectEqual(1, mutations[1].removedNodes.length);
- testing.expectEqual(oldChildren[1], mutations[1].removedNodes[0]);
- testing.expectEqual(0, mutations[1].addedNodes.length);
-
- testing.expectEqual('childList', mutations[2].type);
- testing.expectEqual(1, mutations[2].removedNodes.length);
- testing.expectEqual(oldChildren[2], mutations[2].removedNodes[0]);
- testing.expectEqual(0, mutations[2].addedNodes.length);
-
- // Last 3: additions (unwrapped span elements)
- testing.expectEqual('childList', mutations[3].type);
- testing.expectEqual(0, mutations[3].removedNodes.length);
- testing.expectEqual(1, mutations[3].addedNodes.length);
- testing.expectEqual('SPAN', mutations[3].addedNodes[0].nodeName);
-
- testing.expectEqual('childList', mutations[4].type);
- testing.expectEqual(0, mutations[4].removedNodes.length);
- testing.expectEqual(1, mutations[4].addedNodes.length);
- testing.expectEqual('SPAN', mutations[4].addedNodes[0].nodeName);
-
- testing.expectEqual('childList', mutations[5].type);
- testing.expectEqual(0, mutations[5].removedNodes.length);
- testing.expectEqual(1, mutations[5].addedNodes.length);
- testing.expectEqual('SPAN', mutations[5].addedNodes[0].nodeName);
- });
+<script id="childlist_inner_html" type=module>
+ const state = await testing.async();
+ const innerHtmlParent = document.getElementById('inner-html-parent');
+ const oldChildren = Array.from(innerHtmlParent.children);
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(innerHtmlParent, { childList: true });
+
+ // No whitespace between tags to avoid text node mutations
+ innerHtmlParent.innerHTML = '<span>New 1</span><span>New 2</span><span>New 3</span>';
+
+ await state.done((mutations) => {
+ // innerHTML triggers mutations for both removals and additions
+ // With tri-state: from_parser=true + parse_mode=fragment -> mutations fire
+ // HTML wrapper element is filtered out, so: 3 removals + 3 additions = 6
+ testing.expectEqual(6, mutations.length);
+
+ // First 3: removals
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(1, mutations[0].removedNodes.length);
+ testing.expectEqual(oldChildren[0], mutations[0].removedNodes[0]);
+ testing.expectEqual(0, mutations[0].addedNodes.length);
+
+ testing.expectEqual('childList', mutations[1].type);
+ testing.expectEqual(1, mutations[1].removedNodes.length);
+ testing.expectEqual(oldChildren[1], mutations[1].removedNodes[0]);
+ testing.expectEqual(0, mutations[1].addedNodes.length);
+
+ testing.expectEqual('childList', mutations[2].type);
+ testing.expectEqual(1, mutations[2].removedNodes.length);
+ testing.expectEqual(oldChildren[2], mutations[2].removedNodes[0]);
+ testing.expectEqual(0, mutations[2].addedNodes.length);
+
+ // Last 3: additions (unwrapped span elements)
+ testing.expectEqual('childList', mutations[3].type);
+ testing.expectEqual(0, mutations[3].removedNodes.length);
+ testing.expectEqual(1, mutations[3].addedNodes.length);
+ testing.expectEqual('SPAN', mutations[3].addedNodes[0].nodeName);
+
+ testing.expectEqual('childList', mutations[4].type);
+ testing.expectEqual(0, mutations[4].removedNodes.length);
+ testing.expectEqual(1, mutations[4].addedNodes.length);
+ testing.expectEqual('SPAN', mutations[4].addedNodes[0].nodeName);
+
+ testing.expectEqual('childList', mutations[5].type);
+ testing.expectEqual(0, mutations[5].removedNodes.length);
+ testing.expectEqual(1, mutations[5].addedNodes.length);
+ testing.expectEqual('SPAN', mutations[5].addedNodes[0].nodeName);
});
</script>
diff --git a/src/browser/tests/mutation_observer/multiple_observers.html b/src/browser/tests/mutation_observer/multiple_observers.html
index 850aee649..1166cc94a 100644
--- a/src/browser/tests/mutation_observer/multiple_observers.html
+++ b/src/browser/tests/mutation_observer/multiple_observers.html
@@ -2,46 +2,47 @@
<div id="target">Test</div>
<script src="../testing.js"></script>
-<script id="multiple_observers">
- testing.async(async () => {
- const element = document.getElementById('target');
-
- let records1 = null;
- let records2 = null;
- let callbackCount = 0;
-
- const observer1 = new MutationObserver((records) => {
- records1 = records;
- observer1.disconnect();
- callbackCount++;
- });
-
- const observer2 = new MutationObserver((records) => {
- records2 = records;
- observer2.disconnect();
- callbackCount++;
- });
-
- observer1.observe(element, { attributes: true });
- observer2.observe(element, { attributes: true, attributeOldValue: true });
-
- element.setAttribute('data-foo', 'bar');
- element.setAttribute('data-foo', 'baz');
-
- Promise.resolve().then(() => {
- testing.expectEqual(2, callbackCount);
- testing.expectEqual(2, records1.length);
- testing.expectEqual(2, records2.length);
-
- testing.expectEqual('data-foo', records1[0].attributeName);
- testing.expectEqual(null, records1[0].oldValue);
- testing.expectEqual('data-foo', records1[1].attributeName);
- testing.expectEqual(null, records1[1].oldValue);
-
- testing.expectEqual('data-foo', records2[0].attributeName);
- testing.expectEqual(null, records2[0].oldValue);
- testing.expectEqual('data-foo', records2[1].attributeName);
- testing.expectEqual('bar', records2[1].oldValue);
- });
+<script id="multiple_observers" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('target');
+
+ let records1 = null;
+ let records2 = null;
+ let callbackCount = 0;
+
+ const observer1 = new MutationObserver((records) => {
+ records1 = records;
+ observer1.disconnect();
+ callbackCount++;
+ });
+
+ const observer2 = new MutationObserver((records) => {
+ records2 = records;
+ observer2.disconnect();
+ callbackCount++;
+ });
+
+ observer1.observe(element, { attributes: true });
+ observer2.observe(element, { attributes: true, attributeOldValue: true });
+
+ element.setAttribute('data-foo', 'bar');
+ element.setAttribute('data-foo', 'baz');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(2, callbackCount);
+ testing.expectEqual(2, records1.length);
+ testing.expectEqual(2, records2.length);
+
+ testing.expectEqual('data-foo', records1[0].attributeName);
+ testing.expectEqual(null, records1[0].oldValue);
+ testing.expectEqual('data-foo', records1[1].attributeName);
+ testing.expectEqual(null, records1[1].oldValue);
+
+ testing.expectEqual('data-foo', records2[0].attributeName);
+ testing.expectEqual(null, records2[0].oldValue);
+ testing.expectEqual('data-foo', records2[1].attributeName);
+ testing.expectEqual('bar', records2[1].oldValue);
});
</script>
diff --git a/src/browser/tests/mutation_observer/mutation_observer.html b/src/browser/tests/mutation_observer/mutation_observer.html
index b80c37c2c..ff301053b 100644
--- a/src/browser/tests/mutation_observer/mutation_observer.html
+++ b/src/browser/tests/mutation_observer/mutation_observer.html
@@ -5,133 +5,133 @@
<div id="test-element-4">Test</div>
<script src="../testing.js"></script>
-<script id="mutation_observer">
- testing.async(async () => {
- const element = document.getElementById('test-element-1');
+<script id="mutation_observer" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-1');
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(element, { attributes: true });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(element, { attributes: true });
- element.setAttribute('data-foo', 'bar');
- element.setAttribute('class', 'changed');
- element.removeAttribute('data-foo');
+ element.setAttribute('data-foo', 'bar');
+ element.setAttribute('class', 'changed');
+ element.removeAttribute('data-foo');
- Promise.resolve().then(() => {
- testing.expectEqual(3, mutations.length);
+ await state.done((mutations) => {
+ testing.expectEqual(3, mutations.length);
- testing.expectEqual('attributes', mutations[0].type);
- testing.expectEqual(element, mutations[0].target);
- testing.expectEqual('data-foo', mutations[0].attributeName);
- testing.expectEqual(null, mutations[0].oldValue);
+ testing.expectEqual('attributes', mutations[0].type);
+ testing.expectEqual(element, mutations[0].target);
+ testing.expectEqual('data-foo', mutations[0].attributeName);
+ testing.expectEqual(null, mutations[0].oldValue);
- testing.expectEqual('attributes', mutations[1].type);
- testing.expectEqual(element, mutations[1].target);
- testing.expectEqual('class', mutations[1].attributeName);
- testing.expectEqual(null, mutations[1].oldValue);
+ testing.expectEqual('attributes', mutations[1].type);
+ testing.expectEqual(element, mutations[1].target);
+ testing.expectEqual('class', mutations[1].attributeName);
+ testing.expectEqual(null, mutations[1].oldValue);
- testing.expectEqual('attributes', mutations[2].type);
- testing.expectEqual(element, mutations[2].target);
- testing.expectEqual('data-foo', mutations[2].attributeName);
- testing.expectEqual(null, mutations[2].oldValue);
- });
+ testing.expectEqual('attributes', mutations[2].type);
+ testing.expectEqual(element, mutations[2].target);
+ testing.expectEqual('data-foo', mutations[2].attributeName);
+ testing.expectEqual(null, mutations[2].oldValue);
});
</script>
-<script id="mutation_observer_old_value">
- testing.async(async () => {
- const element = document.getElementById('test-element-2');
+<script id="mutation_observer_old_value" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-2');
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(element, { attributes: true, attributeOldValue: true });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(element, { attributes: true, attributeOldValue: true });
- element.setAttribute('data-test', 'value1');
- element.setAttribute('data-test', 'value2');
- element.removeAttribute('data-test');
+ element.setAttribute('data-test', 'value1');
+ element.setAttribute('data-test', 'value2');
+ element.removeAttribute('data-test');
- Promise.resolve().then(() => {
- testing.expectEqual(3, mutations.length);
+ await state.done((mutations) => {
+ testing.expectEqual(3, mutations.length);
- testing.expectEqual('data-test', mutations[0].attributeName);
- testing.expectEqual(null, mutations[0].oldValue);
+ testing.expectEqual('data-test', mutations[0].attributeName);
+ testing.expectEqual(null, mutations[0].oldValue);
- testing.expectEqual('data-test', mutations[1].attributeName);
- testing.expectEqual('value1', mutations[1].oldValue);
+ testing.expectEqual('data-test', mutations[1].attributeName);
+ testing.expectEqual('value1', mutations[1].oldValue);
- testing.expectEqual('data-test', mutations[2].attributeName);
- testing.expectEqual('value2', mutations[2].oldValue);
- });
+ testing.expectEqual('data-test', mutations[2].attributeName);
+ testing.expectEqual('value2', mutations[2].oldValue);
});
</script>
-<script id="mutation_observer_disconnect">
- testing.async(async () => {
- const element = document.getElementById('test-element-3');
+<script id="mutation_observer_disconnect" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-3');
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
- observer.observe(element, { attributes: true });
- observer.disconnect();
+ observer.observe(element, { attributes: true });
+ observer.disconnect();
- element.setAttribute('data-disconnected', 'test');
+ element.setAttribute('data-disconnected', 'test');
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(false, callbackCalled);
});
</script>
-<script id="mutation_observer_take_records">
- testing.async(async () => {
- const element = document.getElementById('test-element-4');
+<script id="mutation_observer_take_records" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('test-element-4');
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
- observer.observe(element, { attributes: true });
- element.setAttribute('data-take', 'records');
+ observer.observe(element, { attributes: true });
+ element.setAttribute('data-take', 'records');
- const taken = observer.takeRecords();
+ const taken = observer.takeRecords();
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(1, taken.length);
testing.expectEqual('data-take', taken[0].attributeName);
-
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- });
+ testing.expectEqual(false, callbackCalled);
});
</script>
-<script id="microtask_access_to_records">
- testing.async(async () => {
- let savedRecords;
- const promise = new Promise((resolve) => {
- const element = document.createElement('div');
- const observer = new MutationObserver((records) => {
- // Save the records array itself
- savedRecords = records;
- resolve();
- observer.disconnect();
- });
- observer.observe(element, { attributes: true });
- element.setAttribute('test', 'value');
+<script id="microtask_access_to_records" type=module>
+ const state = await testing.async();
+ let savedRecords;
+ const promise = new Promise((resolve) => {
+ const element = document.createElement('div');
+ const observer = new MutationObserver((records) => {
+ // Save the records array itself
+ savedRecords = records;
+ resolve();
+ observer.disconnect();
});
+ observer.observe(element, { attributes: true });
+ element.setAttribute('test', 'value');
+ });
- await promise;
- // Force arena reset by making a Zig call
- document.getElementsByTagName('*');
+ await promise;
+ // Force arena reset by making a Zig call
+ document.getElementsByTagName('*');
+ state.resolve();
+ await state.done(() => {
testing.expectEqual(1, savedRecords.length);
testing.expectEqual('attributes', savedRecords[0].type);
testing.expectEqual('test', savedRecords[0].attributeName);
diff --git a/src/browser/tests/mutation_observer/mutations_during_callback.html b/src/browser/tests/mutation_observer/mutations_during_callback.html
index 938e45183..6baf4176c 100644
--- a/src/browser/tests/mutation_observer/mutations_during_callback.html
+++ b/src/browser/tests/mutation_observer/mutations_during_callback.html
@@ -2,38 +2,36 @@
<div id="target">Test</div>
<script src="../testing.js"></script>
-<script id="mutations_during_callback">
- testing.async(async () => {
- const element = document.getElementById('target');
+<script id="mutations_during_callback" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('target');
- let callCount = 0;
- let firstRecords = null;
- let secondRecords = null;
+ let callCount = 0;
+ let firstRecords = null;
+ let secondRecords = null;
- const observer = new MutationObserver((records) => {
- callCount++;
- if (callCount === 1) {
- firstRecords = records;
- element.setAttribute('data-second', 'from-callback');
- } else if (callCount === 2) {
- secondRecords = records;
- observer.disconnect();
- }
- });
+ const observer = new MutationObserver((records) => {
+ callCount++;
+ if (callCount === 1) {
+ firstRecords = records;
+ element.setAttribute('data-second', 'from-callback');
+ } else if (callCount === 2) {
+ secondRecords = records;
+ observer.disconnect();
+ }
+ });
- observer.observe(element, { attributes: true });
+ observer.observe(element, { attributes: true });
- element.setAttribute('data-first', 'initial');
+ element.setAttribute('data-first', 'initial');
- Promise.resolve().then(() => {
- // After first microtask, first callback should have run and triggered second mutation
- }).then(() => {
- // After second microtask, second callback should have run
- testing.expectEqual(2, callCount);
- testing.expectEqual(1, firstRecords.length);
- testing.expectEqual('data-first', firstRecords[0].attributeName);
- testing.expectEqual(1, secondRecords.length);
- testing.expectEqual('data-second', secondRecords[0].attributeName);
- });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(2, callCount);
+ testing.expectEqual(1, firstRecords.length);
+ testing.expectEqual('data-first', firstRecords[0].attributeName);
+ testing.expectEqual(1, secondRecords.length);
+ testing.expectEqual('data-second', secondRecords[0].attributeName);
});
</script>
diff --git a/src/browser/tests/mutation_observer/observe_multiple_targets.html b/src/browser/tests/mutation_observer/observe_multiple_targets.html
index c45475267..8fc547f61 100644
--- a/src/browser/tests/mutation_observer/observe_multiple_targets.html
+++ b/src/browser/tests/mutation_observer/observe_multiple_targets.html
@@ -3,29 +3,27 @@
<div id="target2">Test2</div>
<script src="../testing.js"></script>
-<script id="observe_multiple_targets">
- testing.async(async () => {
- const element1 = document.getElementById('target1');
- const element2 = document.getElementById('target2');
+<script id="observe_multiple_targets" type=module>
+ const state = await testing.async();
+ const element1 = document.getElementById('target1');
+ const element2 = document.getElementById('target2');
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
- observer.observe(element1, { attributes: true });
- observer.observe(element2, { attributes: true });
+ observer.observe(element1, { attributes: true });
+ observer.observe(element2, { attributes: true });
- element1.setAttribute('data-one', 'value1');
- element2.setAttribute('data-two', 'value2');
+ element1.setAttribute('data-one', 'value1');
+ element2.setAttribute('data-two', 'value2');
- Promise.resolve().then(() => {
- testing.expectEqual(2, mutations.length);
- testing.expectEqual(element1, mutations[0].target);
- testing.expectEqual('data-one', mutations[0].attributeName);
- testing.expectEqual(element2, mutations[1].target);
- testing.expectEqual('data-two', mutations[1].attributeName);
- });
+ await state.done((mutations) => {
+ testing.expectEqual(2, mutations.length);
+ testing.expectEqual(element1, mutations[0].target);
+ testing.expectEqual('data-one', mutations[0].attributeName);
+ testing.expectEqual(element2, mutations[1].target);
+ testing.expectEqual('data-two', mutations[1].attributeName);
});
</script>
diff --git a/src/browser/tests/mutation_observer/reobserve_same_target.html b/src/browser/tests/mutation_observer/reobserve_same_target.html
index 9249fbaca..488ca0a03 100644
--- a/src/browser/tests/mutation_observer/reobserve_same_target.html
+++ b/src/browser/tests/mutation_observer/reobserve_same_target.html
@@ -2,26 +2,24 @@
<div id="target">Test</div>
<script src="../testing.js"></script>
-<script id="reobserve_same_target">
- testing.async(async () => {
- const element = document.getElementById('target');
+<script id="reobserve_same_target" type=module>
+ const state = await testing.async();
+ const element = document.getElementById('target');
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
- observer.observe(element, { attributes: true, attributeOldValue: false });
- observer.observe(element, { attributes: true, attributeOldValue: true });
+ observer.observe(element, { attributes: true, attributeOldValue: false });
+ observer.observe(element, { attributes: true, attributeOldValue: true });
- element.setAttribute('data-foo', 'value1');
- element.setAttribute('data-foo', 'value2');
+ element.setAttribute('data-foo', 'value1');
+ element.setAttribute('data-foo', 'value2');
- Promise.resolve().then(() => {
- testing.expectEqual(2, mutations.length);
- testing.expectEqual(null, mutations[0].oldValue);
- testing.expectEqual('value1', mutations[1].oldValue);
- });
+ await state.done((mutations) => {
+ testing.expectEqual(2, mutations.length);
+ testing.expectEqual(null, mutations[0].oldValue);
+ testing.expectEqual('value1', mutations[1].oldValue);
});
</script>
diff --git a/src/browser/tests/mutation_observer/subtree.html b/src/browser/tests/mutation_observer/subtree.html
index 6492a20e8..88fadcfae 100644
--- a/src/browser/tests/mutation_observer/subtree.html
+++ b/src/browser/tests/mutation_observer/subtree.html
@@ -16,123 +16,116 @@
</div>
<script src="../testing.js"></script>
-<script id="subtree_attributes">
- testing.async(async () => {
- const grandparent = document.getElementById('grandparent');
- const child = document.getElementById('child');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(grandparent, { attributes: true, subtree: true });
-
- child.setAttribute('data-test', 'changed');
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('attributes', mutations[0].type);
- testing.expectEqual(child, mutations[0].target);
- testing.expectEqual('data-test', mutations[0].attributeName);
- });
+<script id="subtree_attributes" type=module>
+ const state = await testing.async();
+ const grandparent = document.getElementById('grandparent');
+ const child = document.getElementById('child');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(grandparent, { attributes: true, subtree: true });
+
+ child.setAttribute('data-test', 'changed');
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('attributes', mutations[0].type);
+ testing.expectEqual(child, mutations[0].target);
+ testing.expectEqual('data-test', mutations[0].attributeName);
});
</script>
-<script id="subtree_attributes_without_subtree">
- testing.async(async () => {
- const grandparent = document.getElementById('grandparent');
- const child = document.getElementById('child');
+<script id="subtree_attributes_without_subtree" type=module>
+ const state = await testing.async();
+ const grandparent = document.getElementById('grandparent');
+ const child = document.getElementById('child');
- let callbackCalled = false;
- const observer = new MutationObserver(() => {
- callbackCalled = true;
- });
- observer.observe(grandparent, { attributes: true, subtree: false });
+ let callbackCalled = false;
+ const observer = new MutationObserver(() => {
+ callbackCalled = true;
+ });
+ observer.observe(grandparent, { attributes: true, subtree: false });
- child.setAttribute('data-no-subtree', 'test');
+ child.setAttribute('data-no-subtree', 'test');
- Promise.resolve().then(() => {
- testing.expectEqual(false, callbackCalled);
- observer.disconnect();
- });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ observer.disconnect();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(false, callbackCalled);
});
</script>
-<script id="subtree_character_data">
- testing.async(async () => {
- const grandparent = document.getElementById('text-grandparent');
- const container = document.getElementById('text-container');
- const textNode = container.firstChild;
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(grandparent, {
- characterData: true,
- characterDataOldValue: true,
- subtree: true
- });
-
- textNode.data = 'Changed text';
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('characterData', mutations[0].type);
- testing.expectEqual(textNode, mutations[0].target);
- testing.expectEqual('Text here', mutations[0].oldValue);
- });
+<script id="subtree_character_data" type=module>
+ const state = await testing.async();
+ const grandparent = document.getElementById('text-grandparent');
+ const container = document.getElementById('text-container');
+ const textNode = container.firstChild;
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(grandparent, {
+ characterData: true,
+ characterDataOldValue: true,
+ subtree: true
+ });
+
+ textNode.data = 'Changed text';
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('characterData', mutations[0].type);
+ testing.expectEqual(textNode, mutations[0].target);
+ testing.expectEqual('Text here', mutations[0].oldValue);
});
</script>
-<script id="subtree_childlist">
- testing.async(async () => {
- const grandparent = document.getElementById('childlist-grandparent');
- const parent = document.getElementById('childlist-parent');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
- observer.observe(grandparent, { childList: true, subtree: true });
-
- const newChild = document.createElement('div');
- newChild.textContent = 'New child';
- parent.appendChild(newChild);
-
- Promise.resolve().then(() => {
- testing.expectEqual(1, mutations.length);
- testing.expectEqual('childList', mutations[0].type);
- testing.expectEqual(parent, mutations[0].target);
- testing.expectEqual(1, mutations[0].addedNodes.length);
- testing.expectEqual(newChild, mutations[0].addedNodes[0]);
- });
+<script id="subtree_childlist" type=module>
+ const state = await testing.async();
+ const grandparent = document.getElementById('childlist-grandparent');
+ const parent = document.getElementById('childlist-parent');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+ observer.observe(grandparent, { childList: true, subtree: true });
+
+ const newChild = document.createElement('div');
+ newChild.textContent = 'New child';
+ parent.appendChild(newChild);
+
+ await state.done((mutations) => {
+ testing.expectEqual(1, mutations.length);
+ testing.expectEqual('childList', mutations[0].type);
+ testing.expectEqual(parent, mutations[0].target);
+ testing.expectEqual(1, mutations[0].addedNodes.length);
+ testing.expectEqual(newChild, mutations[0].addedNodes[0]);
});
</script>
-<script id="subtree_deep_nesting">
- testing.async(async () => {
- const root = document.createElement('div');
- const child = document.createElement('div');
-
- let mutations = null;
- const observer = new MutationObserver((records) => {
- observer.disconnect();
- mutations = records;
- });
-
- root.appendChild(child);
- observer.observe(root, { attributes: true, subtree: true });
- child.setAttribute('data-deep', 'value');
-
- Promise.resolve().then(() => {
- const lastMutation = mutations[mutations.length - 1];
- testing.expectEqual('attributes', lastMutation.type);
- testing.expectEqual(child, lastMutation.target);
- testing.expectEqual('data-deep', lastMutation.attributeName);
- });
+<script id="subtree_deep_nesting" type=module>
+ const state = await testing.async();
+ const root = document.createElement('div');
+ const child = document.createElement('div');
+
+ const observer = new MutationObserver((records) => {
+ observer.disconnect();
+ state.resolve(records);
+ });
+
+ root.appendChild(child);
+ observer.observe(root, { attributes: true, subtree: true });
+ child.setAttribute('data-deep', 'value');
+
+ await state.done((mutations) => {
+ const lastMutation = mutations[mutations.length - 1];
+ testing.expectEqual('attributes', lastMutation.type);
+ testing.expectEqual(child, lastMutation.target);
+ testing.expectEqual('data-deep', lastMutation.attributeName);
});
</script>
diff --git a/src/browser/tests/net/request.html b/src/browser/tests/net/request.html
index 8ebf24cc3..2bfa1829e 100644
--- a/src/browser/tests/net/request.html
+++ b/src/browser/tests/net/request.html
@@ -141,63 +141,58 @@
}
</script>
-<script id=body_methods>
- testing.async(async () => {
- const req = new Request('https://example.com/api', {
- method: 'POST',
- body: 'Hello, World!',
- headers: { 'Content-Type': 'text/plain' }
- });
+<script id=body_methods type=module>
+ const state = await testing.async();
- const text = await req.text();
- testing.expectEqual('Hello, World!', text);
+ const req1 = new Request('https://example.com/api', {
+ method: 'POST',
+ body: 'Hello, World!',
+ headers: { 'Content-Type': 'text/plain' }
});
+ const text1 = await req1.text();
- testing.async(async () => {
- const req = new Request('https://example.com/api', {
- method: 'POST',
- body: '{"name": "test"}',
- headers: { 'Content-Type': 'application/json' }
- });
+ const req2 = new Request('https://example.com/api', {
+ method: 'POST',
+ body: '{"name": "test"}',
+ headers: { 'Content-Type': 'application/json' }
+ });
+ const json2 = await req2.json();
- const json = await req.json();
- testing.expectEqual('test', json.name);
+ const req3 = new Request('https://example.com/api', {
+ method: 'POST',
+ body: 'binary data',
+ headers: { 'Content-Type': 'application/octet-stream' }
});
+ const buffer3 = await req3.arrayBuffer();
- testing.async(async () => {
- const req = new Request('https://example.com/api', {
- method: 'POST',
- body: 'binary data',
- headers: { 'Content-Type': 'application/octet-stream' }
- });
+ const req4 = new Request('https://example.com/api', {
+ method: 'POST',
+ body: 'blob content',
+ headers: { 'Content-Type': 'text/plain' }
+ });
+ const blob4 = await req4.blob();
- const buffer = await req.arrayBuffer();
- testing.expectEqual(true, buffer instanceof ArrayBuffer);
- testing.expectEqual(11, buffer.byteLength);
+ const req5 = new Request('https://example.com/api', {
+ method: 'POST',
+ body: 'bytes'
});
+ const bytes5 = await req5.bytes();
- testing.async(async () => {
- const req = new Request('https://example.com/api', {
- method: 'POST',
- body: 'blob content',
- headers: { 'Content-Type': 'text/plain' }
- });
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('Hello, World!', text1);
- const blob = await req.blob();
- testing.expectEqual(true, blob instanceof Blob);
- testing.expectEqual(12, blob.size);
- testing.expectEqual('text/plain', blob.type);
- });
+ testing.expectEqual('test', json2.name);
- testing.async(async () => {
- const req = new Request('https://example.com/api', {
- method: 'POST',
- body: 'bytes'
- });
+ testing.expectEqual(true, buffer3 instanceof ArrayBuffer);
+ testing.expectEqual(11, buffer3.byteLength);
+
+ testing.expectEqual(true, blob4 instanceof Blob);
+ testing.expectEqual(12, blob4.size);
+ testing.expectEqual('text/plain', blob4.type);
- const bytes = await req.bytes();
- testing.expectEqual(true, bytes instanceof Uint8Array);
- testing.expectEqual(5, bytes.length);
+ testing.expectEqual(true, bytes5 instanceof Uint8Array);
+ testing.expectEqual(5, bytes5.length);
});
</script>
@@ -217,31 +212,38 @@
}
</script>
-<script id=body_used>
- testing.async(async () => {
- const req = new Request('https://example.com', { method: 'POST', body: 'hi' });
- testing.expectFalse(req.bodyUsed);
- await req.text();
- testing.expectTrue(req.bodyUsed);
-
- // Re-consuming a used body rejects.
- let rejected = false;
- try { await req.text(); } catch (e) { rejected = true; }
- testing.expectTrue(rejected);
- });
+<script id=body_used type=module>
+ const state = await testing.async();
- testing.async(async () => {
- // A request with no body is never "used".
- const req = new Request('https://example.com');
- testing.expectFalse(req.bodyUsed);
- await req.text();
- testing.expectFalse(req.bodyUsed);
- });
+ const req1 = new Request('https://example.com', { method: 'POST', body: 'hi' });
+ const usedBefore1 = req1.bodyUsed;
+ await req1.text();
+ const usedAfter1 = req1.bodyUsed;
+
+ // Re-consuming a used body rejects.
+ let rejected1 = false;
+ try { await req1.text(); } catch (e) { rejected1 = true; }
+
+ // A request with no body is never "used".
+ const req2 = new Request('https://example.com');
+ const usedBefore2 = req2.bodyUsed;
+ await req2.text();
+ const usedAfter2 = req2.bodyUsed;
+
+ // text() decodes as UTF-8, stripping a leading BOM.
+ const req3 = new Request('https://example.com', { method: 'POST', body: 'hi' });
+ const text3 = await req3.text();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectFalse(usedBefore1);
+ testing.expectTrue(usedAfter1);
+ testing.expectTrue(rejected1);
+
+ testing.expectFalse(usedBefore2);
+ testing.expectFalse(usedAfter2);
- testing.async(async () => {
- // text() decodes as UTF-8, stripping a leading BOM.
- const req = new Request('https://example.com', { method: 'POST', body: 'hi' });
- testing.expectEqual('hi', await req.text());
+ testing.expectEqual('hi', text3);
});
</script>
diff --git a/src/browser/tests/net/response.html b/src/browser/tests/net/response.html
index 38f8e74ad..0a80ab573 100644
--- a/src/browser/tests/net/response.html
+++ b/src/browser/tests/net/response.html
@@ -48,183 +48,183 @@
}
</script>
-<script id=body_methods>
- testing.async(async () => {
- const response = new Response('Hello, World!');
- const text = await response.text();
- testing.expectEqual('Hello, World!', text);
- });
+<script id=body_methods type=module>
+ const state = await testing.async();
- testing.async(async () => {
- const response = new Response('{"name": "test"}');
- const json = await response.json();
- testing.expectEqual('test', json.name);
- });
+ const response1 = new Response('Hello, World!');
+ const text1 = await response1.text();
- testing.async(async () => {
- const response = new Response('binary data');
- const buffer = await response.arrayBuffer();
- testing.expectEqual(true, buffer instanceof ArrayBuffer);
- testing.expectEqual(11, buffer.byteLength);
- });
+ const response2 = new Response('{"name": "test"}');
+ const json2 = await response2.json();
- testing.async(async () => {
- const response = new Response('blob content', {
- headers: { 'Content-Type': 'text/plain' }
- });
- const blob = await response.blob();
- testing.expectEqual(true, blob instanceof Blob);
- testing.expectEqual(12, blob.size);
- testing.expectEqual('text/plain', blob.type);
+ const response3 = new Response('binary data');
+ const buffer3 = await response3.arrayBuffer();
+
+ const response4 = new Response('blob content', {
+ headers: { 'Content-Type': 'text/plain' }
});
+ const blob4 = await response4.blob();
+
+ const response5 = new Response('bytes');
+ const bytes5 = await response5.bytes();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('Hello, World!', text1);
+
+ testing.expectEqual('test', json2.name);
+
+ testing.expectEqual(true, buffer3 instanceof ArrayBuffer);
+ testing.expectEqual(11, buffer3.byteLength);
+
+ testing.expectEqual(true, blob4 instanceof Blob);
+ testing.expectEqual(12, blob4.size);
+ testing.expectEqual('text/plain', blob4.type);
- testing.async(async () => {
- const response = new Response('bytes');
- const bytes = await response.bytes();
- testing.expectEqual(true, bytes instanceof Uint8Array);
- testing.expectEqual(5, bytes.length);
+ testing.expectEqual(true, bytes5 instanceof Uint8Array);
+ testing.expectEqual(5, bytes5.length);
});
</script>
-<script id=clone>
- {
- const response1 = new Response('test body', {
- status: 201,
- statusText: 'Created',
- headers: { 'X-Custom': 'value' }
- });
+<script id=clone type=module>
+ const state = await testing.async();
- const response2 = response1.clone();
+ const syncResponse1 = new Response('test body', {
+ status: 201,
+ statusText: 'Created',
+ headers: { 'X-Custom': 'value' }
+ });
+ const syncResponse2 = syncResponse1.clone();
- testing.expectEqual(response1.status, response2.status);
- testing.expectEqual(response1.statusText, response2.statusText);
- testing.expectEqual('value', response2.headers.get('X-Custom'));
- }
+ const cloneResponse1 = new Response('cloned body');
+ const cloneResponse2 = cloneResponse1.clone();
- testing.async(async () => {
- const response1 = new Response('cloned body');
- const response2 = response1.clone();
+ const cloneText1 = await cloneResponse1.text();
+ const cloneText2 = await cloneResponse2.text();
- const text1 = await response1.text();
- const text2 = await response2.text();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(syncResponse1.status, syncResponse2.status);
+ testing.expectEqual(syncResponse1.statusText, syncResponse2.statusText);
+ testing.expectEqual('value', syncResponse2.headers.get('X-Custom'));
- testing.expectEqual('cloned body', text1);
- testing.expectEqual('cloned body', text2);
+ testing.expectEqual('cloned body', cloneText1);
+ testing.expectEqual('cloned body', cloneText2);
});
</script>
-<script id=body_types>
+<script id=body_types type=module>
+ const state = await testing.async();
+
// Test Response with ArrayBuffer body
- testing.async(async () => {
- const data = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
- const arrayBuffer = data.buffer;
- const response = new Response(arrayBuffer);
-
- const result = await response.arrayBuffer();
- testing.expectEqual(true, result instanceof ArrayBuffer);
- testing.expectEqual(5, result.byteLength);
-
- const view = new Uint8Array(result);
- testing.expectEqual(72, view[0]); // 'H'
- testing.expectEqual(111, view[4]); // 'o'
- });
+ const arrayBufferData = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
+ const arrayBuffer = arrayBufferData.buffer;
+ const arrayBufferResponse = new Response(arrayBuffer);
+ const arrayBufferResult = await arrayBufferResponse.arrayBuffer();
+ const arrayBufferView = new Uint8Array(arrayBufferResult);
// Test Response with Uint8Array body
- testing.async(async () => {
- const data = new Uint8Array([87, 111, 114, 108, 100]); // "World"
- const response = new Response(data);
+ const uint8Data = new Uint8Array([87, 111, 114, 108, 100]); // "World"
+ const uint8Response = new Response(uint8Data);
+ const uint8Result = await uint8Response.arrayBuffer();
+ const uint8View = new Uint8Array(uint8Result);
- const result = await response.arrayBuffer();
- testing.expectEqual(true, result instanceof ArrayBuffer);
- testing.expectEqual(5, result.byteLength);
+ // Test Response with Blob body
+ const blob = new Blob(['Test', 'Data'], { type: 'text/plain' });
+ const blobResponse = new Response(blob);
+ const blobText = await blobResponse.text();
- const view = new Uint8Array(result);
- testing.expectEqual(87, view[0]); // 'W'
- testing.expectEqual(100, view[4]); // 'd'
+ // Test Response with ReadableStream body
+ const chunks = [
+ new Uint8Array([65, 66, 67]), // "ABC"
+ new Uint8Array([68, 69, 70]) // "DEF"
+ ];
+ let chunkIndex = 0;
+
+ const stream = new ReadableStream({
+ pull(controller) {
+ if (chunkIndex < chunks.length) {
+ controller.enqueue(chunks[chunkIndex++]);
+ } else {
+ controller.close();
+ }
+ }
});
- // Test Response with Blob body
- testing.async(async () => {
- const blob = new Blob(['Test', 'Data'], { type: 'text/plain' });
- const response = new Response(blob);
+ const streamResponse = new Response(stream);
+ const streamResult = await streamResponse.arrayBuffer();
+ const streamView = new Uint8Array(streamResult);
- const text = await response.text();
- testing.expectEqual('TestData', text);
+ // Test Response.body returns ReadableStream
+ const bodyStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array([1, 2, 3]));
+ controller.close();
+ }
});
- // Test Response with ReadableStream body
- testing.async(async () => {
- const chunks = [
- new Uint8Array([65, 66, 67]), // "ABC"
- new Uint8Array([68, 69, 70]) // "DEF"
- ];
- let chunkIndex = 0;
-
- const stream = new ReadableStream({
- pull(controller) {
- if (chunkIndex < chunks.length) {
- controller.enqueue(chunks[chunkIndex++]);
- } else {
- controller.close();
- }
- }
- });
+ const bodyStreamResponse = new Response(bodyStream);
+ const body = bodyStreamResponse.body;
- const response = new Response(stream);
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, arrayBufferResult instanceof ArrayBuffer);
+ testing.expectEqual(5, arrayBufferResult.byteLength);
+ testing.expectEqual(72, arrayBufferView[0]); // 'H'
+ testing.expectEqual(111, arrayBufferView[4]); // 'o'
- const result = await response.arrayBuffer();
- testing.expectEqual(true, result instanceof ArrayBuffer);
- testing.expectEqual(6, result.byteLength);
+ testing.expectEqual(true, uint8Result instanceof ArrayBuffer);
+ testing.expectEqual(5, uint8Result.byteLength);
+ testing.expectEqual(87, uint8View[0]); // 'W'
+ testing.expectEqual(100, uint8View[4]); // 'd'
- const view = new Uint8Array(result);
- testing.expectEqual(65, view[0]); // 'A'
- testing.expectEqual(66, view[1]); // 'B'
- testing.expectEqual(67, view[2]); // 'C'
- testing.expectEqual(68, view[3]); // 'D'
- testing.expectEqual(69, view[4]); // 'E'
- testing.expectEqual(70, view[5]); // 'F'
- });
+ testing.expectEqual('TestData', blobText);
- // Test Response.body returns ReadableStream
- testing.async(async () => {
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(new Uint8Array([1, 2, 3]));
- controller.close();
- }
- });
+ testing.expectEqual(true, streamResult instanceof ArrayBuffer);
+ testing.expectEqual(6, streamResult.byteLength);
+ testing.expectEqual(65, streamView[0]); // 'A'
+ testing.expectEqual(66, streamView[1]); // 'B'
+ testing.expectEqual(67, streamView[2]); // 'C'
+ testing.expectEqual(68, streamView[3]); // 'D'
+ testing.expectEqual(69, streamView[4]); // 'E'
+ testing.expectEqual(70, streamView[5]); // 'F'
- const response = new Response(stream);
- const body = response.body;
testing.expectEqual(true, body instanceof ReadableStream);
});
</script>
-<script id=body_used>
- testing.async(async () => {
- const response = new Response('hi');
- testing.expectFalse(response.bodyUsed);
- await response.text();
- testing.expectTrue(response.bodyUsed);
-
- // Re-consuming a used body rejects.
- let rejected = false;
- try { await response.text(); } catch (e) { rejected = true; }
- testing.expectTrue(rejected);
- });
+<script id=body_used type=module>
+ const state = await testing.async();
- testing.async(async () => {
- // A bodyless response is never "used".
- const response = new Response();
- testing.expectFalse(response.bodyUsed);
- await response.text();
- testing.expectFalse(response.bodyUsed);
- });
+ const response1 = new Response('hi');
+ const usedBefore1 = response1.bodyUsed;
+ await response1.text();
+ const usedAfter1 = response1.bodyUsed;
+
+ // Re-consuming a used body rejects.
+ let rejected1 = false;
+ try { await response1.text(); } catch (e) { rejected1 = true; }
+
+ // A bodyless response is never "used".
+ const response2 = new Response();
+ const usedBefore2 = response2.bodyUsed;
+ await response2.text();
+ const usedAfter2 = response2.bodyUsed;
+
+ // text() decodes as UTF-8, stripping a leading BOM.
+ const response3 = new Response('hi');
+ const text3 = await response3.text();
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectFalse(usedBefore1);
+ testing.expectTrue(usedAfter1);
+ testing.expectTrue(rejected1);
+
+ testing.expectFalse(usedBefore2);
+ testing.expectFalse(usedAfter2);
- testing.async(async () => {
- // text() decodes as UTF-8, stripping a leading BOM.
- const response = new Response('hi');
- testing.expectEqual('hi', await response.text());
+ testing.expectEqual('hi', text3);
});
</script>
diff --git a/src/browser/tests/notification.html b/src/browser/tests/notification.html
index 667ef3d00..13348c3a2 100644
--- a/src/browser/tests/notification.html
+++ b/src/browser/tests/notification.html
@@ -9,10 +9,13 @@
}
</script>
-<script id=Notification#requestPermission>
+<script id=Notification#requestPermission type=module>
{
- testing.async(async () => {
- testing.expectEqual("default", await Notification.requestPermission());
+ const state = await testing.async();
+ const permission = await Notification.requestPermission();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("default", permission);
});
}
</script>
diff --git a/src/browser/tests/performance_observer/performance_observer.html b/src/browser/tests/performance_observer/performance_observer.html
index 38e1607b9..e4911e3bc 100644
--- a/src/browser/tests/performance_observer/performance_observer.html
+++ b/src/browser/tests/performance_observer/performance_observer.html
@@ -37,8 +37,8 @@
}
</script>
-<script id="microtask_access_to_list">
-{
+<script id="microtask_access_to_list" type=module>
+ const state = await testing.async();
let savedList;
const promise = new Promise((resolve) => {
@@ -51,18 +51,23 @@
performance.mark("testMark");
});
- testing.async(async () => {
- await promise;
- // force a call_depth reset, which will clear the call_arena
- document.getElementsByTagName('*');
-
- const entries = savedList.getEntries();
- testing.expectEqual(true, entries instanceof Array, {script_id: 'microtask_access_to_list'});
- testing.expectEqual(1, entries.length);
- testing.expectEqual("testMark", entries[0].name);
- testing.expectEqual("mark", entries[0].entryType);
+ await promise;
+ // force a call_depth reset, which will clear the call_arena
+ document.getElementsByTagName('*');
+
+ const entries = savedList.getEntries();
+ const entriesIsArray = entries instanceof Array;
+ const entriesLen = entries.length;
+ const firstName = entries[0].name;
+ const firstType = entries[0].entryType;
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, entriesIsArray);
+ testing.expectEqual(1, entriesLen);
+ testing.expectEqual("testMark", firstName);
+ testing.expectEqual("mark", firstType);
});
-}
</script>
<script>
@@ -152,6 +157,10 @@
let receivedEntries = null;
const observer = new PerformanceObserver((list) => {
receivedEntries = list.getEntries();
+ // Disconnect as soon as the buffered entries arrive so later marks
+ // (e.g. from other tests sharing the global performance buffer) don't
+ // trigger a second callback that overwrites receivedEntries.
+ observer.disconnect();
});
// With buffered: true, existing marks should be delivered
@@ -162,8 +171,6 @@
testing.expectEqual(2, receivedEntries.length);
testing.expectEqual("early1", receivedEntries[0].name);
testing.expectEqual("early2", receivedEntries[1].name);
-
- observer.disconnect();
});
}
</script>
diff --git a/src/browser/tests/testing.js b/src/browser/tests/testing.js
index 1b3978f7b..7adb75427 100644
--- a/src/browser/tests/testing.js
+++ b/src/browser/tests/testing.js
@@ -75,41 +75,35 @@
});
}
- async function async(cb) {
+ async function async() {
const script_id = (IS_TEST_RUNNER) ? document.currentScript.id : 'cannot track module id in FF/Chrome';
- if (cb == undefined) {
- if (async_seen.has(script_id)) {
- throw new Error(`testing.async() called more than once for script '${script_id}'. A script may only register one async block (the runner can declare success in the gap between two of them); split the test into separate <script> tags.`);
- }
- async_seen.add(script_id);
-
- let resolve = null
- const promise = new Promise((r) => { resolve = r});
- async_pending.add(script_id);
-
- return {
- promise: promise,
- resolve: resolve,
- capture: {script_id: script_id, stack: new Error().stack},
- done: async function(cb) {
- const res = await this.promise;
- async_pending.delete(script_id);
- async_capture = this.capture;
- try {
- cb(res);
- } catch (err) {
- console.warn(script_id, err);
- failed = true;
- }
- async_capture = false;
- }
- };
+ if (async_seen.has(script_id)) {
+ throw new Error(`testing.async() called more than once for script '${script_id}'. A script may only register one async block (the runner can declare success in the gap between two of them); split the test into separate <script> tags.`);
}
-
- let capture = {script_id: script_id, stack: new Error().stack};
- await cb(() => { async_capture = capture; });
- async_capture = null;
+ async_seen.add(script_id);
+
+ let resolve = null
+ const promise = new Promise((r) => { resolve = r});
+ async_pending.add(script_id);
+
+ return {
+ promise: promise,
+ resolve: resolve,
+ capture: {script_id: script_id, stack: new Error().stack},
+ done: async function(cb) {
+ const res = await this.promise;
+ async_pending.delete(script_id);
+ async_capture = this.capture;
+ try {
+ cb(res);
+ } catch (err) {
+ console.warn(script_id, err);
+ failed = true;
+ }
+ async_capture = false;
+ }
+ };
}
function assertOk() {
@@ -149,7 +143,7 @@
}
function printTimeoutState() {
- console.warn('Pending count:', Array.from(async_pending.keys()));
+ console.warn('Pending count:', Array.from(async_pending.keys()));
}
const IS_TEST_RUNNER = window.navigator.userAgent.startsWith("Lightpanda/");