Сбой теста компонента: TypeError: Невозможно прочитать свойство 'user' из null во внедренной службе - PullRequest
0 голосов
/ 09 апреля 2019

Я запускаю тест «Создать» на компоненте, который я ожидаю пройти, но он не работает с:

TypeError: Cannot read property 'user' of null

У меня есть компонент (keys-settings), который использует сервис (ProfileProvider),который, в свою очередь, использует другую службу (AuthService).

ProfileProvider имеет идентификатор участника, который инициализируется извлечением значения 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;
  }

Жасминовому тесту не удается прочитать .user.idкоторый вызывает ошибку.

Функция конструктора вызывается при инициализации класса, тогда как ngOnit вызывается после конструктора, после создания компонента.

Если я переместлю ...

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

из конструктора в ngOnit () {}, тест пройден, однако this.id затем оценивается как неопределенный.

Я попытался установить значение id:

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

, которое не работает.

Если я жестко закодировал значение в ProfileProvider, тест проходит без проблем.


Реализовано предложение Угура Динча:

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 голосов
/ 09 апреля 2019

Вы должны смоделировать getResult в вашем authService следующим образом:

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';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...