编写异步测试
并非所有测试都能立即执行,有些可能需要执行“阻塞”操作,如获取资源和/或其他零碎的操作。为了适应这种情况,还通过 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 编译器兼容性
请注意,async
函数仅在 Rust 1.39.0 及更高版本的稳定版中受支持。
如果您使用的是 crates.io 中的 futures
crate 的 0.1 版本,那么您需要使用 wasm-bindgen-futures
的 0.3.*
版本和 wasm-bindgen-test
的 0.2.8
版本。在这些模式下,您还需要使用 #[wasm_bindgen_test(async)]
而不是使用 async
函数。总的来说,我们建议使用带有 async
的 nightly 版本,因为用户体验会好很多!