我有一项我想测试的服务:
@Injectable()
export class AuthenticationService {
initialAuthStatus = this.authenticationStatus.first();
constructor(private adalService: AdalService,
private settingsProvider: SettingsProvider) { }
public get authenticationStatus(): any {
return this.adalService.userInfo.authenticationStatus;
}
}
对服务的测试:
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();
}));
});
但是,测试失败并显示以下错误消息:
AuthenticationService should be created
TypeError: Cannot read property 'authenticationStatus' of undefined
它与身份验证状态的获取有关,但我无法确切地知道它失败的原因。
非常感谢任何帮助:)
答案 0 :(得分:0)
在该行的顶部,在此行中,您声明了类属性initialAuthStatus
:
initialAuthStatus = this.authenticationStatus.first();
this.authenticationStatus
尚未初始化,为您提供错误消息。
为了使它工作,将该行放在ngOnInit()方法中,并将纯声明部分保留在类的顶部。
initialAuthStatus;
...
ngOnInit(){
this.initialAuthStatus = this.authenticationStatus;
}
...
...