leptos/leptos_reactive/tests/effect.rs

90 lines
2.1 KiB
Rust
Raw Normal View History

use leptos_reactive::create_scope;
2022-08-08 18:09:16 +00:00
#[test]
fn effect_runs() {
use std::cell::RefCell;
use std::rc::Rc;
create_scope(|cx| {
2022-08-08 18:09:16 +00:00
let (a, set_a) = cx.create_signal(-1);
// simulate an arbitrary side effect
let b = Rc::new(RefCell::new(String::new()));
cx.create_effect({
let b = b.clone();
move |_| {
2022-08-08 18:09:16 +00:00
let formatted = format!("Value is {}", a());
*b.borrow_mut() = formatted;
}
});
assert_eq!(b.borrow().as_str(), "Value is -1");
set_a(|a| *a = 1);
assert_eq!(b.borrow().as_str(), "Value is 1");
})
.dispose()
2022-08-08 18:09:16 +00:00
}
#[test]
fn effect_tracks_memo() {
use std::cell::RefCell;
use std::rc::Rc;
create_scope(|cx| {
2022-08-08 18:09:16 +00:00
let (a, set_a) = cx.create_signal(-1);
let b = cx.create_memo(move |_| format!("Value is {}", a()));
2022-08-08 18:09:16 +00:00
// simulate an arbitrary side effect
let c = Rc::new(RefCell::new(String::new()));
cx.create_effect({
let c = c.clone();
move |_| {
2022-08-08 18:09:16 +00:00
*c.borrow_mut() = b();
}
});
assert_eq!(b().as_str(), "Value is -1");
assert_eq!(c.borrow().as_str(), "Value is -1");
set_a(|a| *a = 1);
assert_eq!(b().as_str(), "Value is 1");
assert_eq!(c.borrow().as_str(), "Value is 1");
})
.dispose()
2022-08-08 18:09:16 +00:00
}
#[test]
fn untrack_mutes_effect() {
use std::cell::RefCell;
use std::rc::Rc;
create_scope(|cx| {
2022-08-08 18:09:16 +00:00
let (a, set_a) = cx.create_signal(-1);
// simulate an arbitrary side effect
let b = Rc::new(RefCell::new(String::new()));
cx.create_effect({
let b = b.clone();
move |_| {
2022-08-08 18:09:16 +00:00
let formatted = format!("Value is {}", cx.untrack(a));
*b.borrow_mut() = formatted;
}
});
assert_eq!(a(), -1);
assert_eq!(b.borrow().as_str(), "Value is -1");
set_a(|a| *a = 1);
assert_eq!(a(), 1);
assert_eq!(b.borrow().as_str(), "Value is -1");
})
.dispose()
2022-08-08 18:09:16 +00:00
}