Prerequisites

Add com.facebook.litho:litho-testing to the dependencies block in the gradle build file.

1
testImplementation 'com.facebook.litho:litho-testing:0.38.0'

Testing components with @TreeProp

While @Props are received from the immediate parent component, a @TreeProp can be passed down to a components from any of its ancestors in the current component hierarchy.

Testing a Component with @TreeProp

When testing hierarchies with a component which uses @TreeProps, those tree props should be be passed down to the components as expected.

1
2
3
4
5
6
7
8
9
10
@LayoutSpec
class ComponentWithTreePropSpec {
  @OnCreateLayout
  static Component onCreateLayout(
      ComponentContext c,
      @Prop String normalProp,
      @TreeProp UserContext userContext) { // <- Should be passed down by ancestors.
    // ...
  }
}

Use LithoViewRule#setTreeProp(Class, Object) to set a @TreeProp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RunWith(LithoTestRunner.class)
public class ComponentWithTreePropTest {

  public final @Rule LithoViewRule mLithoViewRule = new LithoViewRule();

  @Test
  public void test() {
    final ComponentContext c = mLithoViewRule.getContext();
    final Component component = ComponentWithTreeProp.create(c).build();

    mLithoViewRule
      .attachToWindow()
      .setTreeProp(UserContext.class, new UserContext()) // setting tree props for the hierarchy.
      .setRoot(component)
      .measure()
      .layout();

    // test you assertions as usual
  }
}

Next

Either head back to the testing overview or continue with the next section, Testing InjectProps.

Edit on GitHub