Unit testing communication between siblings in Angular 2

808 views Asked by At

How does someone test communication between 2 sibling components in Angular 2? I don't seem to find any viable resource online.

app.component.html

<comp1 #a></comp1>
<comp2 [x]="a.get()"></comp2>

where get() is a function within the comp1 component whose value I'm passing to one of the class variables of component comp2. How can I test this efficiently?

app.component is the parent component of comp1 and comp2 and encloses them.

1

There are 1 answers

0
saruftw On BEST ANSWER

The snippet you've mentioned gives a partial idea. But I think you want to test if changes in one component's data affects the other component's data.

it('should xx', async(() => {
    const fixture = TestBed.createComponent(ParentComponent);
    fixture.detectChanges();

    const child1 = fixture.debugElement.queryAll(By.directive(ChildComponent1))[0];
    const but = child1.queryAll(By.css('#some_element'))[0].nativeElement; // change data in child1
    fixture.detectChanges(); // detect changes

    const child2 = fixture.debugElement.queryAll(By.directive(ChildComponent2))[0];
    const child2info = child2.queryAll(By.css('some_element'))[1].nativeElement.innerHTML;
    expect(child2info).toBe('some_data'); // check if reflected in child2
  }));

So, basically you use By.directive() to fetch the DOM elements for a child component. Once you've done that, you need to edit the DOM using nativeElement.

After editing, use By.directive() again to fetch the DOM elements for the second child component and then further check its DOM for data changes.

Note: For changing the data in ChildComponent1, do something like but.value = "something" (if its an <input> box) and then create an Event before you call detectChanges().