Refactor hello-web example for possible future automated testing

For now there's a Node.js test that works, but we're not actually running it in CI,
and Node is not a dependency of the project.
This commit is contained in:
Brian Carroll 2021-09-19 11:45:02 +01:00
parent c20a2e5740
commit 11f8652ff6
3 changed files with 48 additions and 12 deletions

View file

@ -3,10 +3,10 @@
<div id="output"></div>
<script src="platform/host.js"></script>
<script>
roc_web_platform_run(
"./hello-world.wasm",
document.getElementById("output")
);
const elem = document.getElementById("output");
roc_web_platform_run("./hello-world.wasm", (string_from_roc) => {
elem.textContent = string_from_roc;
});
</script>
</body>
</html>

View file

@ -1,6 +1,4 @@
const test_decoder = true;
async function roc_web_platform_run(wasm_filename, dom_node) {
async function roc_web_platform_run(wasm_filename, callback) {
const decoder = new TextDecoder();
let memory_bytes;
let exit_code;
@ -8,7 +6,7 @@ async function roc_web_platform_run(wasm_filename, dom_node) {
function js_display_roc_string(str_bytes, str_len) {
const utf8_bytes = memory_bytes.subarray(str_bytes, str_bytes + str_len);
const js_string = decoder.decode(utf8_bytes);
dom_node.textContent = js_string;
callback(js_string);
}
const importObj = {
@ -25,10 +23,17 @@ async function roc_web_platform_run(wasm_filename, dom_node) {
},
};
const wasm = await WebAssembly.instantiateStreaming(
fetch(wasm_filename),
importObj
);
let wasm;
const response = await fetch(wasm_filename);
if (WebAssembly.instantiateStreaming) {
// streaming API has better performance if available
wasm = await WebAssembly.instantiateStreaming(response, importObj);
} else {
const module_bytes = await response.arrayBuffer();
wasm = await WebAssembly.instantiate(module_bytes, importObj);
}
memory_bytes = new Uint8Array(wasm.instance.exports.memory.buffer);
@ -41,3 +46,9 @@ async function roc_web_platform_run(wasm_filename, dom_node) {
}
}
}
if (typeof module !== 'undefined') {
module.exports = {
roc_web_platform_run,
};
}

View file

@ -0,0 +1,25 @@
/**
* Node.js test file for hello-web example
* We are not running this in CI currently, and Node.js is not a Roc dependency.
* But if you happen to have it, you can run this.
*/
// Node doesn't have the fetch API
const fs = require("fs/promises");
global.fetch = (filename) =>
fs.readFile(filename).then((buffer) => ({
arrayBuffer() {
return buffer;
},
}));
const { roc_web_platform_run } = require("./platform/host");
roc_web_platform_run("./hello-world.wasm", (string_from_roc) => {
const expected = "Hello, World!";
if (string_from_roc !== expected) {
console.error(`Expected "${expected}", but got "${string_from_roc}"`);
process.exit(1);
}
console.log("OK");
});