【发布时间】:2019-08-29 21:19:45
【问题描述】:
我的 Angular 8 网络应用程序有一个组件,它根据路由执行不同的操作。在ngOnInit 中,我使用路由数据来检查cached 参数是否存在。我正在尝试编写一个单元测试,将cached 设置为true,因此它进入ngOnInit 中的if 语句,但它不起作用。我做错了什么?
home.component.ts
cached = false;
constructor(private backend: APIService, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.cached = this.activatedRoute.snapshot.data['cached'];
if (this.cached)
{
this.getCached();
}
else
{
this.fetchFromAPI();
}
}
home.component.spec.ts
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let service: APIService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
RouterTestingModule,
],
declarations: [
HomeComponent,
],
providers: [
APIService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
service = TestBed.get(APIService);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should go into if cached statement', fakeAsync(() => {
component.cached = true;
component.ngOnInit();
const dummyData = [
{ id: 1, name: 'testing' }
];
spyOn(service, 'fetchCachedData').and.callFake(() => {
return from([dummyData]);
});
expect(service.fetchCachedData).toHaveBeenCalled();
}));
})
路由器模块
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'view-cache', component: HomeComponent, data: {cached: true}},
];
【问题讨论】:
-
我如何在测试中访问它?