Search code examples
angularkarma-jasmineangular-test

Call created spy before change detection


I want to call created spy method before change detection is triggered. here is my mocked class.

const stubStudentService: Pick<StudentsCrudService, keyof StudentsCrudService> =
  {
    getAllStudents: jasmine
      .createSpy('getAllStudents')
      .and.returnValue(of(studentPayload)),
     ...other methods
  };

How do I call that getAllStudents before fixture.detectChanges()

 beforeEach(() => {
    fixture = TestBed.createComponent(StudentsListComponent);
    component = fixture.componentInstance;
    <-- want to call that spy here --->
    fixture.detectChanges();
  });

I wanted to do this because of this issue. but can't figure out how to change the solution according to my mocked service https://stackoverflow.com/questions/69989284/...


Solution

  • You need to use TestBed.inject here:

    beforeEach(() => {
      TestBed.configureTestingModule({
        // ...
        providers: [
          {
            provide: StudentsCrudService,
            useValue: stubStudentService,
          },
        ],
      });
    });
    
    beforeEach(() => {
      fixture = TestBed.createComponent(StudentsListComponent);
      component = fixture.componentInstance;
    
      const studentsCrudService = TestBed.inject(StudentsCrudService);
      // spyOn(studentsCrudService, 'getAllStudents')...;
    
      fixture.detectChanges();
    });