我正在使用具有构造函数的Angular 2组件中的Jasmine Karma编写测试用例。在这个构造函数中,我将其他组件对象作为参数传递。当试图访问其他组件的方法时,未定义。
1。 TestComponent
@Component({
template: `<div></div>`
})
class TestComponent implements OnInit {
constructor(public otherComponent: OtherComponent) {}
ngOnInit() {}
callMyFunction() {
this.otherComponent.otherFunction();
}
}
2。其他组件
@Component({
selector: "other-component",
template: `<div></div>`
})
export class OtherComponent implements OnInit {
ngOnInit() {}
public otherFunction(): void {
console.log('test function called');
}
}
第3。测试用例
describe("TestComponent", () => {
let comp: TestComponent;
let fixture: ComponentFixture < TestComponent > ;
let de: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestComponent, OtherComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
comp = fixture.componentInstance;
de = fixture.debugElement;
fixture.detectChanges();
});
fit("Should call otherFunction of OtherComponent.", () => {
spyOn(comp.otherComponent, "otherFunction").and.callThrough();
comp.callMyFunction();
expect(comp.otherComponent.otherFunction).toHaveBeenCalled();
});
});
请帮我解决这个问题。