Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it’s suited for websites, Node.js projects, or anywhere that JavaScript can run.
How to reproduce it
routing.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-routing',
templateUrl: './routing.component.html',
styleUrls: [ './routing.component.css' ]
})
export class RoutingComponent {
param: string = "";
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(param => {
this.param = param[ 'id' ];
})
}
}
routing.component.spec.ts
...
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ RoutingComponent ],
providers:
[
{
provide: ActivatedRoute,
useValue: mockActivatedRoute
}
]
})
.compileComponents();
fixture = TestBed.createComponent(RoutingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
...
Error message:
TypeError: Cannot read properties of undefined (reading 'subscribe')
at RoutingComponent.call [as ngOnInit] (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/routing/routing/routing.component.ts:18:23)
at callHook (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:2488:22)
at callHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:2457:17)
at executeInitAndCheckHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:2408:9)
at refreshView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:10434:21)
at detectChangesInternal (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:11624:9)
at RootViewRef.detectChanges (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:12115:9)
at ComponentFixture._tick (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/testing.mjs:126:32)
at apply (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/testing.mjs:139:22)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:375:26)
Solution
Create an observable mockup.
...
const mockActivatedRoute = {
params: of({ id: '123' })
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ RoutingComponent ],
providers:
[
{
provide: ActivatedRoute,
useValue: mockActivatedRoute
}
]
})
.compileComponents();
...