Angular 2 中兄弟姐妹之间的单元测试通信

Unit testing communication between siblings in Angular 2

有人如何测试 Angular 2 中两个同级组件之间的通信?我似乎没有在网上找到任何可行的资源。

app.component.html

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

其中 get()comp1 组件中的一个函数,我将其值传递给组件 comp2 的 class 变量之一。我怎样才能有效地测试它?

app.componentcomp1comp2 的父组件并包围它们。

您提到的片段给出了部分想法。但我认为您想测试一个组件数据的变化是否会影响另一个组件的数据。

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
  }));

所以,基本上您使用 By.directive() 来获取子组件的 DOM 元素。完成后,您需要使用 nativeElement 编辑 DOM。

编辑后,再次使用By.directive()获取第二个子组件的DOM个元素,然后进一步检查其DOM是否有数据变化。

注意: 要更改 ChildComponent1 中的数据,请执行类似 but.value = "something" 的操作(如果它是 <input> 框),然后在调用 detectChanges() 之前创建一个 Event