【问题标题】:Karma: Cannot read property * of undefined业力:无法读取未定义的属性 *
【发布时间】:2018-07-27 07:27:17
【问题描述】:

我想测试一项服务:

@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

它与身份验证状态的getter有关,但我无法弄清楚它失败的确切原因。

非常感谢任何帮助:)

【问题讨论】:

  • 错误来自这一行:initialAuthStatus = this.authenticationStatus.first();那时它还没有被初始化
  • 我该如何解决?
  • 将其放入构造函数或 ngOnInit 中,然后将 initialAuthStatus 留在顶部
  • 哇,好吧,我真的是瞎了。我现在已经把它放在了 ngOnInit 中(构造函数没有工作),它现在可以工作了。感谢日志:) 请写一个帖子,以便我可以将其标记为答案。

标签: javascript angular typescript jasmine karma-jasmine


【解决方案1】:

在类的顶部,在这一行中,您声明类属性initialAuthStatus

initialAuthStatus = this.authenticationStatus.first();

this.authenticationStatus 还没有初始化,给你错误信息。 为了使它工作,将该行放在 ngOnInit() 方法中,并将纯声明部分保留在类的顶部。

initialAuthStatus;
...
ngOnInit(){
    this.initialAuthStatus = this.authenticationStatus;
}
...
...

【讨论】:

  • 这就是解决方案!但是,这是 ngOnInit() 中的 this.initialAuthStatus :) 感谢您的帮助 :)
猜你喜欢
  • 2015-01-13
  • 2020-12-29
  • 2018-07-24
  • 2021-09-28
  • 2017-06-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多