Unit testing can be done by using the Dom::assert_eq function, whichtests your DOM against a certain XML string:

  1. struct DataModel;
  2.  
  3. fn render_counter(count: usize) -> Dom<DataModel> {
  4. Dom::div().with_class("test").with_child(
  5. Dom::label(format!("{}", count))
  6. )
  7. }
  8.  
  9. #[test]
  10. fn test_counter_ui() {
  11. let expected = r#"
  12. <div class="test">
  13. <p>5</p>
  14. </div>
  15. "#;
  16.  
  17. let dom = render_counter(5);
  18.  
  19. dom.assert_eq(expected);
  20. }

You can technically also use assert_eq!(expected, got);, however, if the test fails,the Dom::assert_eq error message has a much nicer format:

  1. thread 'widgets::test_counter_ui' panicked at '
  2. Expected DOM did not match:
  3.  
  4. expected: ----------
  5. <div/>
  6. <div class="test"/>
  7. <p>4</p>
  8. </div>
  9. </div>
  10.  
  11. got: ----------
  12. <div/>
  13. <div class="test"/>
  14. <p>5</p>
  15. </div>
  16. </div>

Good Practices

  • Typedef the name of your DataModel in your main.rs, so that it it easier to changein future projects.
  • It's also a good idea to typedef the &'a AppState<DataModel> and the &'a mut CallbackInfo,in order to keep the code cleaner:
  1. pub type DataModel = AppData;
  2. pub type State<'a> = &'a mut AppState<DataModel>;
  3. pub type CbInfo<'a, 'b> = &'a mut CallbackInfo<'b, DataModel>;

This way you can avoid a bit of typing work since rustc is smart enough to inferthe lifetimes - your callbacks should now look like this:

  1. fn my_callback(state: State, cb: CbInfo) -> Dom<DataModel> { /* */ }