I am writing unit tests for my component but having trouble in creating the instance of the component and showing following error,
TypeError: Cannot read property 'patientId' of null
I have tried mocking all the providers including router and active router My component.ts is
export class PatientInsurancePlanSearchComponent implements OnInit {
private patientId: number = -1;
public selectedOrganizationInsurance: OrganizationInsurance;
public organizationInsurancePlans$: Observable<OrganizationInsurancePlan[]>;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private biilingHttpService: BillingHttpService
) {
this.selectedOrganizationInsurance = new OrganizationInsurance();
}
ngOnInit() {
this.patientId = history.state.patientId as number;
this.selectedOrganizationInsurance = history.state.selectedOrganizationInsurance as OrganizationInsurance;
this.organizationInsurancePlans$ = this.biilingHttpService.getOrganizationInsurancePlans(this.selectedOrganizationInsurance.id);
}
spec.ts
class FakeInsurancePlanSearchComponent {
@Input() public organizationInsurancePlans: OrganizationInsurancePlan[] = [];
@Input() public selectedOrganizationInsurance: OrganizationInsurance;
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PatientInsurancePlanSearchComponent
, FakeInsurancePlanSearchComponent ],
imports: [
StoreModule.forRoot({}),
HttpClientModule,
RouterTestingModule,
],
providers: [
Store,
{
provide: ActivatedRoute, useValue: {
state: of({ selectedorganizationInsurancePlan: 'AETNA'})
}
},
BillingHttpService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PatientInsurancePlanSearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
Kindly guide me whats i am missing..
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
In a unit test, mock objects can simulate the behavior of complex, real objects and are therefore useful when it is impractical or impossible to incorporate a real object into a unit test. Mocking makes sense in a unit testing context.
Mocking is the act of creating something that looks like the dependency but is something we control in our test. There are a few methods we can use to create mocks.
If you want to add patientId to the browsers session history stack, you can simply use:
history.pushState(state, title, url);
In your case it should be something like this:
describe(MyComponent.name, () => {
...
beforeEach(() => {
window.history.pushState({ patientId: 'somevalue'}, '', '');
...
})
it('...', () => {
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With