My component class is simple. It takes an input from parent component and based on that input it resolves a parameter from an ENUM inside the ngOnInit
My Component class:
export class TestComponent implements OnInit {
@Input() serviceType: string;
serviceUrl : string;
ngOnInit() {
this.findServiceType();
}
findServiceType= () => {
if (this.serviceType) {
if (this.serviceType === 't1') {
this.serviceUrl = TestFileEnumConstants.T1_URL;
}else if (this.serviceType === 't2') {
this.serviceUrl = TestFileEnumConstants.T2_URL;
}
}
}
}
describe('testcomponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let mockService = <Serv1>{};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
TestComponent, TestChildComponent],
providers: [
{ provide: MockService, useValue: mockService }
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should create testcomponent', () => {
expect(component).toBeDefined();
});
describe('testType1', () => {
beforeEach( () => {
spyOn(component, 'findServiceType');
});
it('should correctly wire url based on type1', () => {
component.serviceType = 'type1';
fixture.detectChanges();
expect(component.findServiceType).toHaveBeenCalled();
expect(component.serviceUrl).toBe(TestFileEnumConstants.T1_URL)
});
});
}
The issue is serviceUrl
is not getting poluplated because 'serviceType' - the input is coming as undefined
even after change detection is called.
The issue was because of a SpyOn
statement in the beforEach()
segment. Since the mock function is not returning any data, the return value keep on getting undefined
. The problem statement is given below, I have to comment the spyOn
statement:
beforeEach( () => {
// spyOn(component, 'findServiceType');
});
Removed this function and worked fine.