Home > Net >  Angular Testing - createSpyObj method not called
Angular Testing - createSpyObj method not called

Time:10-09

I have one Angular component and one service. In the component I have a method which calls one method of the service. At the component test I try to create a mock for the service, then when I call the method of the component I would like to check if the service method was called from the component.

The component:

export class TestComponent {

  constructor(private testService: TestService) {}

  edit(): void {
    this.testService.getCase('id').subscribe(console.log);
  }
}

The service:

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor(
    private http: HttpClient,
  ) { }

  getCase(id: string): Observable<any> {
    return this.http.get<any>(`url`);
  }
}

And the test:

describe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  const testServiceMock = jasmine.createSpyObj('TestService', ['getCase']);
  
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      providers: [
        { provide: TestService, useValue: testServiceMock },
      ]
    })
      .compileComponents();
  });

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

  it('expect service has been called', () => {
    spyOn(component, 'edit');
    component.edit();
    expect(component.edit).toHaveBeenCalledTimes(1);
    expect(testServiceMock.getCase).toHaveBeenCalled();
  });
});

This line is constantly failing:
expect(testServiceMock.getCase).toHaveBeenCalled();

TestComponent expect service has been called FAILED Error: Expected spy TestService.getCase to have been called.

CodePudding user response:

Since the edit method is a spy, the actual implementation never gets called so the getCase spy never gets called as well. In order to resolve this please use the edit method spy with callThrough(). This forces the actual implementation to be called.

spyOn(component,'edit').and.callThrough()

CodePudding user response:

You need to delegate calls to actual implementation:

spyOn(component, 'edit').and.callThrough();

https://jasmine.github.io/2.0/introduction#section-Spies:_and.callThrough

  • Related