Home > Back-end >  Testing Async Functions
Testing Async Functions

Time:09-27

I am using Wasm-Pack and I need to write a unit test for a asynchronous function that references a JavaScript Library. I tried using the futures::executor::block_on in order to get the asynchronous function to return so I could make an assert. However, blocking is not supported in the wasm build target. I can't test in a different target because the asynchronous function I am testing is referencing a JavaScript library. I also don't think I can spawn a new thread and handle the future there, because it need to return to the assert statement in the original thread. What is the best way to go about testing this asynchronous function?

Code being tested in src/lib.rs

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub async fn func_to_test() -> bool {
    return some_long_running_fuction().await;
}

Testing code in tests/web.rs

#![cfg(target_arch = "wasm32")]

extern crate wasm_bindgen_test;
use test_crate;
use futures::executor::block_on;

#[wasm_bindgen_test]
fn can_return_from_async(){
   let ret = block_on(test_crate::func_to_test());
   assert!(ret);
}

How do I test an async function if I can't use any blocking?

CodePudding user response:

Rust can handle tests that are async functions themselves. Just change the test fuction to be async and throw in an await.

#[wasm_bindgen_test]
async fn can_return_from_async(){
    let ret = test_crate::func_to_test().await
    assert!(ret);
}
  • Related