Skip to content

Commit

Permalink
Support running tests in Node.js
Browse files Browse the repository at this point in the history
Run with `wasm-pack test --node`
Needs Node 23 for require(esm)
  • Loading branch information
MattiasBuelens committed Oct 25, 2024
1 parent acee003 commit d64812a
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 16 deletions.
4 changes: 4 additions & 0 deletions tests/js/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "module",
"private": true
}
9 changes: 9 additions & 0 deletions tests/node.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#![cfg(target_arch = "wasm32")]

extern crate wasm_bindgen_test;

wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_node_experimental);

mod js;
mod tests;
mod util;
6 changes: 3 additions & 3 deletions tests/tests/fetch_as_stream.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use futures_util::{AsyncReadExt, TryStreamExt};
use js_sys::Uint8Array;
use js_sys::{global, Uint8Array};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
use wasm_streams::ReadableStream;
use web_sys::{window, Response};
use web_sys::{Response, Window};

#[wasm_bindgen_test]
async fn test_fetch_as_stream() {
// Make a fetch request
let url = "https://rustwasm.github.io/assets/wasm-ferris.png";
let window = window().unwrap_throw();
let window = global().unchecked_into::<Window>(); // hack to also support Node.js
let resp_value = JsFuture::from(window.fetch_with_str(url))
.await
.unwrap_throw();
Expand Down
28 changes: 15 additions & 13 deletions tests/util/unhandled_error_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ impl UnhandledErrorGuard {
}
})
};
for event_type in ERROR_TYPES {
window()
.unwrap()
.add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref())
.unwrap();
if let Some(window) = window() {
for event_type in ERROR_TYPES {
window
.add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref())
.unwrap();
}
}
Self {
errors,
Expand All @@ -47,14 +48,15 @@ impl Default for UnhandledErrorGuard {
impl Drop for UnhandledErrorGuard {
fn drop(&mut self) {
// Remove listeners
for event_type in ERROR_TYPES {
window()
.unwrap()
.add_event_listener_with_callback(
event_type,
self.listener.as_ref().unchecked_ref(),
)
.unwrap();
if let Some(window) = window() {
for event_type in ERROR_TYPES {
window
.add_event_listener_with_callback(
event_type,
self.listener.as_ref().unchecked_ref(),
)
.unwrap();
}
}
// Panic if there are any errors
let errors = self.errors.take();
Expand Down

0 comments on commit d64812a

Please sign in to comment.