撰寫非同步測試
並非所有測試都能立即執行,有些測試可能需要執行「阻塞」工作,例如提取資源和/或其他零碎的東西。為了適應這種情況,也支援透過 futures
和 wasm-bindgen-futures
crate 進行非同步測試。
撰寫非同步測試非常簡單,只需使用 async
函式即可!您也可能想要使用 wasm-bindgen-futures
crate 將 JS promises 轉換為 Rust futures。
# #![allow(unused_variables)] #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 版本,因為使用者體驗會大幅改善!