当行为测试 Angular 个组件时,是否可以查找另一个组件的实例?

When behaviour-testing Angular Components is it possible to lookup the instance of another Component?

我正在测试一个 Angular 工具栏组件,该组件通过 @ngrx/store 触发状态更改操作。

我有另一个组件订阅了这些状态更改以更新它自己的内部状态。

所以在 karma/jasmine 单元测试中,我触发了工具栏按钮的点击。然后我只是想 spy 在另一个组件上并断言它的 change 函数被调用了。

所以问题是,在不使用 ViewParent/ViewChild 指令更改现有组件的情况下,仅用于测试哪些 ofc 将被视为代码气味,我如何查找一个实例Angular组件

我觉得你可能想多了。

@ngrx/store 允许您订阅这个存在于任何组件树之外的通用商店。因此,如果您想将事件发送到您的@ngrx/store 并订阅某个其他组件中的那个@ngrx/store,那么在测试该其他组件时,只需创建您的商店,发送您的事件并查看是否您的被测组件可以正确响应 'store events'。

当您测试发送事件的第一个组件时,监视商店并确认它从您的第一个组件接收到正确的事件。

如果您的测试确认第一个组件正在正确发送事件并且您可以确认第二个组件正确响应事件,那么您已经正确地对通过商店的组件交互的双方进行了单元测试。

可以获取子组件的正确实例,以便像这样测试行为。

您可以通过指令查询父级以查找子级:

import { By } from '@angular/platform-browser';
...
let childComponentInstance: ChildComponent;

// After setting up your component in the TestBed...
parentComponentFixture = TestBed.createComponent(ParentComponent);
...

// Reference the child component from your parent component fixture
childComponentInstance = parentComponentFixture
    .debugElement
    .query(By.directive(ChildComponent))
    .componentInstance;

然后您可以在测试方法中使用 childComponentInstance

如您所述,这不再是真正的单元测试,而更像是行为测试。

(可能需要在 parentComponentFixture 上调用 detectChanges() 以正确加载子项,具体取决于绑定到它的内容)