Reputation: 5770
I have a service which I would like to test:
@Injectable()
export class AuthenticationService {
initialAuthStatus = this.authenticationStatus.first();
constructor(private adalService: AdalService,
private settingsProvider: SettingsProvider) { }
public get authenticationStatus(): any {
return this.adalService.userInfo.authenticationStatus;
}
}
And a test for the service:
describe('AuthenticationService', () => {
let mockAdalService: any;
let adalService: any;
let service: any;
let mockSettingsProvider: any;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthenticationService,
AdalService,
{ provide: SettingsProvider, useClass: MockSettingsProvider },
{ provide: AdalService, useClass: MockAdalService }
]
});
mockAdalService = new MockAdalService();
adalService = new AdalService();
mockSettingsProvider = new MockSettingsProvider();
});
it('should be created', inject([AuthenticationService], (service: AuthenticationService) => {
expect(service).toBeTruthy();
}));
});
However, the test fails with the following error message:
AuthenticationService should be created
TypeError: Cannot read property 'authenticationStatus' of undefined
It has something to do with the getter of authentication status, but I can't figure out exactly why it fails.
Any help is greatly appreciated :)
Upvotes: 3
Views: 15487
Reputation: 28708
At the top of the class, in this line, where you declare the class property initialAuthStatus
:
initialAuthStatus = this.authenticationStatus.first();
this.authenticationStatus
hasn't been initialized yet, gives you the error message.
To make it work, put that line in ngOnInit() method and keep pure declaration part at the top of the class.
initialAuthStatus;
...
ngOnInit(){
this.initialAuthStatus = this.authenticationStatus;
}
...
...
Upvotes: 1