2

I have a function that calls another that itself uses a http subscription, and I am having trouble testing it...

MyComponent

id = 1;

myFunct() {
  this.myService.delete(this.id);
}

MyService

delete(id) {
  this.http.delete(this.myUrl + '/' + id).subscribe()
}

Test

let mockService;

beforeEach(() => {
  TestBed.configureTestingModule({
    mockService = createSpyObj(['delete']);

    imports: ...,
    declarations: ...,
    providers: [
      {provide: MyService, useValue: mockService}
    ]
  }).compileComponents();

  fixture = ...;
  component = ...;
  fixture.detectChanges();
});

it('should test delete', () => {
  mockService.delete.and.returnValue({ subscribe: () => {} });
  component.myFunct();
  expect(mockService.delete).toHaveBeenCalledTimes(1);
});

My test brings back the error:

Cannot read property 'subscribe' of undefined

physicsboy
  • 5,656
  • 17
  • 70
  • 119

1 Answers1

5

The common pattern is to return observable from your service method and subscribe inside eg. component.

Something like this:

MyComponent

 id = 1;

 myFunct() { 
    this.myService.delete(this.id).subscribe( 
     (result) => console.log(result),
     (error) => console.log(error)
 };

MyService

 delete(id): Observable<any> {
   this.http.delete(this.myUrl + '/' + id)
 }

Test

imports {of} from 'rxjs'

let mockService;

beforeEach(() => {
  TestBed.configureTestingModule({
    mockService = createSpyObj(['delete']);

    imports: ...,
    declarations: ...,
    providers: [
      {provide: MyService, useValue: mockService}
    ]
  }).compileComponents();

  fixture = ...;
  component = ...;
  fixture.detectChanges();
});

it('should test delete', () => {
  mockService.delete.and.returnValue(of({id: 1}));
  component.myFunct();
  expect(mockService.delete).toHaveBeenCalledTimes(1);
});
jakubm
  • 412
  • 4
  • 11