javascript - Karma: ไม่สามารถอ่านคุณสมบัติ * ของ undefined
ฉันมีบริการที่ฉันอยากจะทดสอบ:
@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
มันเกี่ยวข้องกับเกตเตอร์ของสถานะการตรวจสอบสิทธิ์ แต่ฉันไม่สามารถเข้าใจได้อย่างชัดเจนว่าทำไมมันถึงล้มเหลว
ความช่วยเหลือใด ๆ จะได้รับการชื่นชมอย่างมาก :)
คำตอบ #1
ที่ด้านบนของคลาส ในบรรทัดนี้ ที่คุณประกาศสมบัติของคลาส initialAuthStatus:
initialAuthStatus = this.authenticationStatus.first();
this.authenticationStatus ยังไม่ได้ถูกเริ่มต้น ทำให้คุณได้รับข้อความแสดงข้อผิดพลาด ในการทำให้มันทำงาน ให้ใส่บรรทัดนั้นในเมธอด ngOnInit() และเก็บส่วนการประกาศบริสุทธิ์ไว้ที่ด้านบนของคลาส
initialAuthStatus;
...
ngOnInit(){
this.initialAuthStatus = this.authenticationStatus;
}
...
...
