編寫非同步測試
並非所有測試都能立即執行,有些可能需要執行「阻塞」工作,例如提取資源和/或其他片段。為了滿足這一點,也支援通過 futures
和 wasm-bindgen-futures
crate 的非同步測試。
編寫非同步測試非常簡單,只需使用 async
函數即可!您可能還會想使用 wasm-bindgen-futures
crate 將 JS promises 轉換為 Rust futures。
#![allow(unused)] fn main() { use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; #[wasm_bindgen_test] async fn my_async_test() { // Create a promise that is ready on the next tick of the micro task queue. let promise = js_sys::Promise::resolve(&JsValue::from(42)); // Convert that promise into a future and make the test wait on it. let x = JsFuture::from(promise).await.unwrap(); assert_eq!(x, 42); } }
Rust 編譯器相容性
請注意,只有 Rust 1.39.0 及更高版本的穩定版才支援 async
函數。
如果您使用的是 crates.io 的 0.1 版本 futures
crate,那麼您會想使用 wasm-bindgen-futures
的 0.3.*
版本和 wasm-bindgen-test
的 0.2.8
版本。在這些模式下,您還需要使用 #[wasm_bindgen_test(async)]
而不是使用 async
函數。一般而言,我們建議使用帶有 async
的 nightly 版本,因為使用者體驗會好很多!