组件测试失败:TypeError:无法在注入的服务上读取null的属性“ user”

时间:2019-04-09 16:41:27

标签: angular jasmine

我正在对我希望通过的组件运行应创建的测试,但是失败了:

TypeError: Cannot read property 'user' of null

我有一个使用服务(ProfileProvider)的组件(关键字设置),而该服务又使用了另一个服务(AuthService)。

ProfileProvider具有一个成员ID,该成员ID通过authService来获取值进行初始化:

export class ProfileProvider {
  private uri: string;
  public id: string;

  constructor(
    private http: HttpClient,
    private config: Configuration,
    private authService: Authentication) {
    this.uri = this.config.getConfigOption('apiUri');
    this.id = this.authService.getResult().user.id;
  }

Jasmine测试无法读取导致错误的.user.id。

构造函数在类初始化时调用,而ngOnit在构造函数之后,组件创建后调用。

如果我移动...

 this.id = this.authService.getResult().user.id;

从构造函数进入ngOnit(){},测试通过,但是this.id然后评估为undefined。

我尝试对id的值进行存根:

 profileProvider = debugElement.injector.get(ProfileProvider);
    profileProvider.businessId = '2';

这不起作用。

如果我在ProfileProvider中对值进行硬编码,则测试将顺利通过。


实施了乌尔·丁(UğurDinç)的建议:

fdescribe('KeywordsSettingsComponent', () => {
  let component: KeywordsSettingsComponent,
  fixture: ComponentFixture<KeywordsSettingsComponent>,
  authService: Authentication,
  addKeywordsSpy: any,
  businessIdSpy: any;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientModule, RouterTestingModule],
      declarations: [ KeywordsSettingsComponent ],
      providers: [Configuration, HttpClient, Authentication]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    authService = TestBed.get(Authentication);
    businessIdSpy = spyOn(authService , "getResult").and.returnValue(of({
      user: {
        id: '2'
      }
    }));

    fixture = TestBed.createComponent(KeywordsSettingsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.ngOnInit();

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });


});

错误已更改为:TypeError: Cannot read property 'id' of undefined

1 个答案:

答案 0 :(得分:0)

您应该像这样在authService中模拟getResult:

TestBed.configureTestingModule({            
    ... // configuration
    })

    authService = TestBed.get(Authentication);
    getResultSpy = spyOn(authService , "getResult").and.returnValue(of({
      user: {
        id: '2'
      }
    }));

    fixture = TestBed.createComponent(InviteComponent);
    component = fixture.componentInstance;

不要忘记导入of

import { of } from 'rxjs/internal/observable/of';