Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/wasm-bindgen-test/asynchronous-tests.md

raw
1 # Writing Asynchronous Tests
2
3 Not all tests can execute immediately and some may need to do "blocking" work
4 like fetching resources and/or other bits and pieces. To accommodate this
5 asynchronous tests are also supported through the `futures` and
6 `wasm-bindgen-futures` crates.
7
8 Writing an asynchronous test is pretty simple, just use an `async` function!
9 You'll also likely want to use the `wasm-bindgen-futures` crate to convert JS
10 promises to Rust futures.
11
12 ```rust
13 use wasm_bindgen::prelude::*;
14 use wasm_bindgen_futures::JsFuture;
15
16 #[wasm_bindgen_test]
17 async fn my_async_test() {
18 // Create a promise that is ready on the next tick of the micro task queue.
19 let promise = js_sys::Promise::resolve(&JsValue::from(42));
20
21 // Convert that promise into a future and make the test wait on it.
22 let x = JsFuture::from(promise).await.unwrap();
23 assert_eq!(x, 42);
24 }
25 ```
26
27 ## Rust compiler compatibility
28
29 Note that `async` functions are only supported in stable from Rust 1.39.0 and
30 beyond.
31
32 If you're using the `futures` crate from crates.io in its 0.1 version then
33 you'll want to use the `0.3.*` version of `wasm-bindgen-futures` and the `0.2.8`
34 version of `wasm-bindgen-test`. In those modes you'll also need to use
35 `#[wasm_bindgen_test(async)]` instead of using an `async` function. In general
36 we'd recommend using the nightly version with `async` since the user experience
37 is much improved!