TypeError: Cannot read property 'pipe' of undefined (jasmine, angular)

Viewed 18872

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>
       </div>
     </div>
 </div>

2 Answers

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'
});

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

Related