我有一个我想测试的服务:
@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
它与身份验证状态的获取器有关,但我无法弄清楚它为什么会失败。
任何帮助是极大的赞赏 :)
在类的顶部,在这一行中,您声明类属性initialAuthStatus
:
initialAuthStatus = this.authenticationStatus.first();
this.authenticationStatus
尚未初始化,为您提供错误消息。为了使它工作,将该行放在 ngOnInit() 方法中,并将纯声明部分保留在类的顶部。
initialAuthStatus;
...
ngOnInit(){
this.initialAuthStatus = this.authenticationStatus;
}
...
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句