Skip to content

Commit

Permalink
Add fetch_json() test harness API
Browse files Browse the repository at this point in the history
This allows fetching JSON test data regardless of whether the environment
has fetch() or not; ShadowRealm does not.

In a ShadowRealm environment, this gets the incubating realm to fetch the
data. Every other environment just executes a function that calls fetch().
  • Loading branch information
ptomato committed Jan 18, 2024
1 parent 75090bc commit 335c6d1
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions docs/writing-tests/testharness-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,29 @@ eventWatcher.wait_for('animationstart').then(t.step_func(function() {
}));
```

### Loading test data from JSON files ###

```eval_rst
.. js:autofunction:: fetch_json
```

Loading test data from a JSON file would normally be accomplished by
something like this:

```js
promise_test(() => fetch('resources/my_data.json').then((res) => res.json()).then(runTests));
function runTests(myData) {
/// ...
}
```

However, `fetch()` is not exposed inside ShadowRealm scopes, so if the
test is to be run inside a ShadowRealm, use `fetch_json()` instead:

```js
promise_test(() => fetch_json('resources/my_data.json').then(runTests));
```

### Utility Functions ###

```eval_rst
Expand Down
9 changes: 9 additions & 0 deletions resources/testharness.js
Original file line number Diff line number Diff line change
Expand Up @@ -4777,6 +4777,15 @@
return "Untitled";
}

/** Fetches a JSON resource and parses it */
async function fetch_json(resource) {
const response = await fetch(resource);
return await response.json();
}
if (!global_scope.GLOBAL || !global_scope.GLOBAL.isShadowRealm()) {
expose(fetch_json, 'fetch_json');
}

/**
* Setup globals
*/
Expand Down
8 changes: 8 additions & 0 deletions tools/serve/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,14 @@ class ShadowRealmHandler(HtmlWrapperHandler):
(async function() {
const r = new ShadowRealm();
r.evaluate("globalThis.self = globalThis; undefined;");
r.evaluate(`func => {
globalThis.fetch_json = (resource) => {
const thenMethod = func(resource);
return new Promise((resolve, reject) => thenMethod((s) => resolve(JSON.parse(s)), reject));
};
}`)((resource) => function (resolve, reject) {
fetch(resource).then(res => res.text(), String).then(resolve, reject);
});
await new Promise(r.evaluate(`
(resolve, reject) => {
(async () => {
Expand Down

0 comments on commit 335c6d1

Please sign in to comment.