mod.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //! Kept in its own file to more easily import into the book
  2. use console_error_panic_hook;
  3. use virtual_dom_rs::prelude::*;
  4. use wasm_bindgen::JsCast;
  5. use web_sys::{Element, Node};
  6. /// A test case that both diffing and patching are working in a real browser
  7. pub struct DiffPatchTest<'a> {
  8. /// Description of the test case.
  9. pub desc: &'static str,
  10. /// The old virtual node.
  11. pub old: VirtualNode,
  12. /// The new virtual node.
  13. pub new: VirtualNode,
  14. /// By default we generate the expected based on `new.to_string()`. You can
  15. /// use this field to override the expected HTML after patching.
  16. pub override_expected: Option<&'a str>,
  17. }
  18. impl<'a> DiffPatchTest<'a> {
  19. pub fn test(&mut self) {
  20. console_error_panic_hook::set_once();
  21. let document = web_sys::window().unwrap().document().unwrap();
  22. // Create a DOM node of the virtual root node
  23. let root_node: Node = self.old.create_dom_node().node;
  24. // Clone since virtual_dom_rs::patch takes ownership of the root node.
  25. let patched_root_node: Node = root_node.clone();
  26. // Generate patches
  27. let patches = virtual_dom_rs::diff(&self.old, &self.new);
  28. // Patch our root node. It should now look like `self.new`
  29. virtual_dom_rs::patch(root_node, &patches);
  30. // Determine the expected outer HTML
  31. let expected_outer_html = match self.override_expected {
  32. Some(ref expected) => expected.to_string(),
  33. None => self.new.to_string(),
  34. };
  35. let actual_outer_html = match patched_root_node.node_type() {
  36. Node::ELEMENT_NODE => patched_root_node.unchecked_into::<Element>().outer_html(),
  37. Node::TEXT_NODE => patched_root_node.text_content().unwrap_or("".into()),
  38. _ => panic!("Unhandled node type"),
  39. };
  40. assert_eq!(&actual_outer_html, &expected_outer_html, "{}", self.desc);
  41. }
  42. }