1

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

app.component.html

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

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

app.component是 and 的父组件,comp1并且comp2包含它们。

4

1 回答 1

1

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

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.

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

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

于 2017-08-29T17:39:28.293 回答