rquickjs_extra_test/
lib.rs1use rquickjs::{
2 AsyncContext, AsyncRuntime, CatchResultExt, CaughtError, Ctx, FromJs, Function, Module, Result,
3 async_with,
4 function::IntoArgs,
5 module::{Evaluated, ModuleDef},
6 promise::MaybePromise,
7};
8
9pub fn test_with<F, R>(func: F)
10where
11 F: FnOnce(rquickjs::Ctx) -> R,
12{
13 let rt = rquickjs::Runtime::new().unwrap();
14 let ctx = rquickjs::Context::full(&rt).unwrap();
15 ctx.with(func);
16}
17
18pub async fn test_async_with<F>(func: F)
19where
20 F: for<'js> FnOnce(Ctx<'js>) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + 'js>>
21 + Send,
22{
23 let rt = AsyncRuntime::new().unwrap();
24 let ctx = AsyncContext::full(&rt).await.unwrap();
25
26 async_with!(ctx => |ctx| {
27 func(ctx).await
28 })
29 .await;
30}
31
32pub async fn call_test<'js, T, A>(ctx: &Ctx<'js>, module: &Module<'js, Evaluated>, args: A) -> T
33where
34 T: FromJs<'js>,
35 A: IntoArgs<'js>,
36{
37 call_test_err(ctx, module, args).await.unwrap()
38}
39
40pub async fn call_test_err<'js, T, A>(
41 ctx: &Ctx<'js>,
42 module: &Module<'js, Evaluated>,
43 args: A,
44) -> std::result::Result<T, CaughtError<'js>>
45where
46 T: FromJs<'js>,
47 A: IntoArgs<'js>,
48{
49 module
50 .get::<_, Function>("test")
51 .catch(ctx)?
52 .call::<_, MaybePromise>(args)
53 .catch(ctx)?
54 .into_future::<T>()
55 .await
56 .catch(ctx)
57}
58
59pub struct ModuleEvaluator;
60
61impl ModuleEvaluator {
62 pub async fn eval_js<'js>(
63 ctx: Ctx<'js>,
64 name: &str,
65 source: &str,
66 ) -> Result<Module<'js, Evaluated>> {
67 let (module, module_eval) = Module::declare(ctx, name, source)?.eval()?;
68 module_eval.into_future::<()>().await?;
69 Ok(module)
70 }
71
72 pub async fn eval_rust<'js, M>(ctx: Ctx<'js>, name: &str) -> Result<Module<'js, Evaluated>>
73 where
74 M: ModuleDef,
75 {
76 let (module, module_eval) = Module::evaluate_def::<M, _>(ctx, name)?;
77 module_eval.into_future::<()>().await?;
78 Ok(module)
79 }
80}