如何在Angular中监视子组件?

时间:2017-07-27 15:43:59

标签: angular

在Angular教程中,他们有一个HeroesComponent与孩子HeroesListComponent的示例。

HeroesListComponent使用HeroesServicegetHeroes()

spyOn内的getHeroes() heroes-list.component.spec.ts,我们可以

spyOn(fixture.debugElement.componentInstance.heroesService, 'getHeroes').and.returnValue(Promise.resolve([]))

我的问题是:如果我在HeroesComponent规范文件中,heroes.component.spec.ts我可以spyOn通过这样的方式HeroesListComponent getHeroes()spyOn(fixture.debugElement.componentInstance.heroesListComponent.heroesService, 'getHeroes').and.returnValue(Promise.resolve([]))

<hero-list>

显然这不起作用,所以我问是否有人可以帮我解决问题。

我想这样做,因为我想在我打开HeroesComponent时测试我的HeroesListComponent是否正确加载。这可能看似重复,因为我已经有一个测试来确保HeroesComponent有效,但我认为它仍然是一个重要的测试,因为我真的想确保我的HeroesService正确加载以及所有子组件也是如此

我还尝试模仿HeroesComponent内部的整个spyOn,而不是使用HeroesListComponent,但我无法使用该语法。当我在heroes.component.spec.ts内时,我不知道如何告诉test()使用模拟对象

谢谢!

2 个答案:

答案 0 :(得分:1)

在单元测试中,除了经过测试的单元之外的所有单元都应该被模拟或存根。原始<hero-list>应替换为mock:

@Component({
  selector: 'hero-list',
  template: ''
})
class MockedHeroesListComponent {}

TestBed.configureTestingModule({
  declarations: [
    HeroesComponent,
    MockedHeroesListComponent
  ]
});

HeroesComponent测试不应该测试 heroesListComponent.heroesService。所有应该断言的是<hero-list>被编译。 heroesListComponent.heroesService应在HeroesListComponent测试中使用真实HeroesListComponent进行测试。

答案 1 :(得分:1)

我有一个存根子组件,我想在其中确认是否根据组件的逻辑调用了其上的某些函数。

我能够通过以下设置实现这一目标。

存根组件:

@Component({selector: 'child-component', template: ''})
class ChildComponentStub {
  someFunction() { /* ... */}
}

测试阶段:

it('should spy on a child component function', () => {
  const childComponent =
           fixture.debugElement.query(By.directive(ChildComponentStub))
               .componentInstance;

  const functionSpy = spyOn(childComponent, 'someFunction').and.callThrough();
       
  // test logic that causes someFunction to be called

  expect(functionSpy).toHaveBeenCalled();
});

(基于解释如何获取对子组件的引用的 this answer