0

I'm trying to fix my unit tests of a component that subscribes to an Observable of the service DataService during ngOnInit(). However, at the moment I'm still getting TypeError: Cannot read properties of undefined (reading 'subscribe').

I tried to create a MockDataService that contains the Observable but it still doesn't work. Even though I'm fairly inexperienced with unit tests, I feel like I've successfully done something similar to this.

startpage.component.ts

...

@Component({
  selector: 'app-startpage',
  templateUrl: './startpage.component.html',
  styleUrls: ['./startpage.component.scss']
})
export class StartpageComponent implements OnInit {

  public data: Data = {};

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
   // error during unit test happens here 
    this.dataService.data$.subscribe((data: Data) => {
      this.data = data;
    });
  }
}

startpage.component.spec.ts

...

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [StartpageComponent],
      imports: [],
      providers: [
        { provide: DataService, useValue: MockDataService }
      ]
    })
      .compileComponents();

    fixture = TestBed.createComponent(StartpageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

// MockDataService 
class MockDataService {
  public data$: Observable<Data> = of({});
}

LukyFoggy
  • 519
  • 8
  • 31
  • 1
    You're using the _class_ as a test double, not an _instance_ of it. Either `useClass: MockDataService` so the injector instantiates it, or `useValue: new MockDataService()`. – jonrsharpe Mar 10 '23 at 12:54
  • Does this answer your question? https://stackoverflow.com/a/58988059/2358409 – uminder Mar 12 '23 at 15:35

0 Answers0