在Angular教程中,他们有一个HeroesComponent
与孩子HeroesListComponent
的示例。
HeroesListComponent
使用HeroesService
到getHeroes()
。
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()
使用模拟对象
谢谢!
答案 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)