Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have an error regarding unit testing in Angular. The error is TypeError: Cannot read property 'pipe' of undefined. For this I used an observable and i tried to test the output of the subscribe. I will appreciate any help! Thank you!

  obs1$: Observable<number>;
  pos=12345;
  constructor(
    private service1: Service) {
  ngOnInit() {
    this.obs1$ = this.service1.retrieveData1(this.pos)
      .pipe(
        map(item => item.value || null))
 let component: ComponentName;
  let fixture: ComponentFixture<ComponentName>;
  const serviceSpy = jasmine.createSpyObj('Service',['retrieveData1']);
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ComponentName],
      providers: [{ provide:Service, useValue: {} }
      .overrideComponent(ComponentName, {
        set: {
          providers: [
            { provide: ComponentName, useValue: serviceSpy }
      .compileComponents();
  beforeEach(() => {
    fixture = TestBed.createComponent(ComponentName);
    component = fixture.componentInstance;
 fit('should retrieve value', done => {
    component.pos = 12345;
    fixture.detectChanges();
    component.obs1$.subscribe(value => {
      expect(value).toEqual(1);
      done();
<div *ngIf="obs1$ | async as obs">
    <div [ngSwitch]="obs" class="col-2 p-0">
      <div *ngSwitchCase="0">
         <p>red</p>

After Creating spy you need to return a dummy/mock observable value as well.

code is expecting a Observable so below approach you can try (in every it block which call service you can add this)

serviceSpy.retrieveData1.and.returnValue(of('mock value as requires'))

or you can mock service like this

let serviceSpy= jasmine.createSpyObj('Service', {
    'retrieveData1': of('mock data'),
    'other': 'some val'
                Thanks, this worked! I stored the mock data in a variable and just put it in the place where you have of('mock data').
– MikhailRatner
                May 10, 2022 at 12:14

You have to return on serviceSpy.retrieveData1 an observable. Simpelst case create one with something like serviceSpy.retrieveData1 = of({value: []}) and provide your data. Because now the mock returns undefined, whereas your component expects an observable to use the function "pipe" on it. Which is not possibile

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.