I am writing a test cases using Jasmine Karma in Angular 2 component which having constructor. In this constructor I am passing other component object as a parameter. When trying to access methods of other component are getting undefined.
1. TestComponent
@Component({
template: `<div></div>`
})
class TestComponent implements OnInit {
constructor(public otherComponent: OtherComponent) {}
ngOnInit() {}
callMyFunction() {
this.otherComponent.otherFunction();
}
}
2. OtherComponent
@Component({
selector: "other-component",
template: `<div></div>`
})
export class OtherComponent implements OnInit {
ngOnInit() {}
public otherFunction(): void {
console.log('test function called');
}
}
3. Test Case
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();
});
});
Please help me on this.