我有一个简单的测试,其结构如下:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BreadcrumbsComponent } from './breadcrumbs.component';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { BreadcrumbsService } from './breadcrumbs.service';
import { multiTranslateHttpLoaderFactory } from 'app/app.component';
fdescribe('BreadcrumbsComponent', () => {
let component: BreadcrumbsComponent;
let translateService: TranslateService;
let fixture: ComponentFixture<BreadcrumbsComponent>;
let translateServiceStub: Partial<TranslateService>;
let translateServiceStub: Partial<TranslateService>;
translateServiceStub = {
getBrowserLang: () => {
return 'de';
},
onLangChange: new EventEmitter(),
};
breadcrumbsServiceStub = {
onUpdateRequest: new Subject(),
updateBreadcrumbs: () => {
}
};
beforeEach((() => {
TestBed.configureTestingModule({
declarations: [BreadcrumbsComponent],
imports: [
RouterTestingModule,
HttpClientTestingModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: multiTranslateHttpLoaderFactory,
deps: [HttpClient]
}
}),
],
providers: [
{provide: TranslateService, useValue: translateServiceStub},
{provide: BreadcrumbsService, useValue: breadcrumbsServiceStub},
]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(BreadcrumbsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
当前抛出此错误,我无法处理:
TypeError:无法读取未定义的属性“ subscribe”
这是我的课程,ngOnInit方法中的一行导致此错误:
export class BreadcrumbsComponent implements OnInit {
breadcrumbs: Breadcrumb[] = [];
constructor(private router: Router,
private activeRoute: ActivatedRoute,
private translate: TranslateService,
private breadcrumbsService: BreadcrumbsService) {
}
ngOnInit() {
this.translate.onLangChange.subscribe(() => this.identifyRoute());
}
...
我在这里做错了什么?要么。有没有办法解决该错误或模拟此行,以便测试能够通过?我真的不知道如何在测试中模拟这一行。
答案 0 :(得分:0)
您可以尝试:
import { of } from 'rxjs';
translateServiceStub = {
getBrowserLang: () => {
return 'de';
},
onLangChange: of({
// whatever object is expected
}),
};