我该如何解决这个问题?
大家好,我对使用 karma 和 jasmine 对 Angular 6 进行单元测试非常陌生
我正在尝试覆盖组件构造函数内部但无法执行的服务。'it' 块 'should create component' 覆盖了构造函数内的行,但服务返回的数据除外。
组件.ts
constructor(public firstService: FirstService, public secondService: SecondService) {
let localData :any
let id = this.secondService.getId()
let initialId = this.secondService.getInitialId()
this.firstService.getRevisions(id, initialId).subscribe((data) => {
if (data && data.content) {
localData = data.content || [];
}
});
}
组件.spec.ts
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let firstService: FirstService;
let secondService: SecondService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [FirstService, SecondService]
})
.compileComponents();
});
beforeEach(() => {
firstService = TestBed.get(FirstService);
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
secondService = TestBed.get(SecondService);
fixture.detectChanges();
});
it('should create Component', () => {
expect(component).toBeTruthy();
const mockData = {
"content": [
{
"name": "String",
}
],
}
spyOn(firstService, "getRevisions").and.callFake(() => {
return of({ mockData });
});
spyOn(secondService, 'getId');
spyOn(secondService, 'getInitialId');
fixture.whenStable().then(() => {
expect(firstService.getRevisions).toHaveBeenCalled();
});
});