I'm currently troubleshooting a unit test for my code (I'm not very experienced with Jasmine) after adding some subscriptions to a service. I'm encountering an issue where the subscriptions are coming up as undefined. I'm not entirely sure about the correct way to include these subscriptions.
Here is a simplified version of my component:
export class AppComponent implements OnInit, AfterViewInit {
isSignedIn = false;
isLoggedIn = false;
signedInSubscription: Subscription;
loggedInSubscription: Subscription;
constructor(
private authenticationService: AuthenticationService,
private router: Router,
private http403Tester: Http403TestService,
) {
this.isLoggedIn = authenticationService.isLoggedIn;
this.isSignedIn = authenticationService.isSignedIn;
this.setEnvironment();
}
async ngOnInit() {
// line 69 below, this is where the error is
this.signedInSubscription = this.authenticationService.observableIsSignedIn.subscribe(item => {
this.isSignedIn = item;
});
this.loggedInSubscription = this.authenticationService.observableIsLoggedIn.subscribe(item => {
this.isLoggedIn = item;
});
}
}
The service:
export class AuthenticationService {
constructor() {
this.observableIsSignedIn = new BehaviorSubject<boolean>(this.isSignedIn);
this.observableIsLoggedIn = new BehaviorSubject<boolean>(this.isLoggedIn);
}
isSignedIn: boolean = null;
isLoggedIn: boolean = null;
observableIsSignedIn: any;
observableIsLoggedIn: any;
The spec:
describe('AppComponent', () => {
let authenticationService: any;
let http403Tester: any;
let router: any;
let component: AppComponent;
beforeEach(() => {
authenticationService = {
isSignedIn: jasmine.createSpy(),
isLoggedIn: jasmine.createSpy(),
observableIsSignedIn: jasmine.createSpy(),
observableIsLoggedIn: jasmine.createSpy(),
};
router = { navigateByUrl: jasmine.createSpy() };
http403Tester = { isAuthenticated: jasmine.createSpy() };
component = new AppComponent(authenticationService, router, http403Tester);
});
describe('ngOnInit()', () => {
it('should navigate to /unauthorised when a 403 status code is returned', async () => {
// Arrange
http403Tester.isAuthenticated.and.returnValue(false);
// Act
await component.ngOnInit();
// Assert
expect(router.navigateByUrl).toHaveBeenCalledWith('/unauthorised');
});
And the error:
TypeError: Cannot read property 'subscribe' of undefined
at AppComponent.<anonymous> (src/app/app.component.ts:69:83)
It seems like using createSpy() is not the correct method for mocking a subscription:
observableIsSignedIn: jasmine.createSpy()
However, I am unsure of the next steps to take or what resources to look into. Any suggestions?