0

I have simple child component:

import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { HistorySession } from './models';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-history-info',
  templateUrl: './history-info.component.html',
  styleUrls: ['./history-info.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class HistoryInfoComponent implements OnInit {
  @Input() sessionLoading: Observable<boolean>;
  @Input() session: Observable<HistorySession>;
  @Input() device: string;

  constructor() {}

  ngOnInit() {}
}

My template looks like this:

<div class="history__info-widget">
  <span class="history__info-widget-title mat-caption">
    START TIME
  </span>
  <span class="round-history__info-widget-content">{{
    (session | async).startTime | date: 'HH:mm'
  }}</span>
</div>

And test is like this:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HistoryInfoComponent } from './history-info.component';

describe('RoundHistoryInfoComponent', () => {
  let component: HistoryInfoComponent;
  let fixture: ComponentFixture<HistoryInfoComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HistoryInfoComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HistoryInfoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

When I run test I get this error:

HistoryInfoComponent › should create

TypeError: Cannot read property 'startTime' of null

Do I have to mock initial value of session.startTime property or what is wrong? How do I mock async observable input()?

sensei
  • 7,044
  • 10
  • 57
  • 125

1 Answers1

0

Since it's a child component, I'd recommend not to pass an observable, but better just the object and let the parent manage the subscription.

But, if you still want to do this, you can use the "of" operator and pass it a mock object HistorySession in the BeforeEach - something like this...

const mockHistorySession = {...}
beforeEach(() => {
    fixture = TestBed.createComponent(HistoryInfoComponent);
    component = fixture.componentInstance;
    component.session = of(mockHistorySession);
    fixture.detectChanges();
  });

You must also do this for the other inputs, otherwise you'll have the same issue.

Eddie Paz
  • 2,219
  • 16
  • 11