1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Why are my angular services not being mocked in unit tests?

Discussão em 'Angular' iniciado por Chris Barr, Setembro 13, 2024.

  1. Chris Barr

    Chris Barr Guest

    I have a pretty simple app component that just calls a method on an injected service

    export class AppComponent implements OnInit {
    readonly userService = inject(UserService);

    ngOnInit(): void {
    this.userService.init();
    }
    }


    I am trying to write unit tests to cover this

    describe('AppComponent', () => {
    let app: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let injectedUserSvc: UserService;

    beforeEach(() => {
    TestBed.configureTestingModule({
    imports: [AppComponent, ToastrModule.forRoot()],
    providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])],
    });

    fixture = TestBed.createComponent(AppComponent);
    app = fixture.componentInstance;
    injectedUserSvc = TestBed.inject(UserService);
    });

    it('should create the app and initialize the user service', () => {
    spyOn(injectedUserSvc, 'init');
    fixture.detectChanges(); //triggers ngOnInit()

    expect(app).toBeTruthy();
    expect(injectedUserSvc.init).toHaveBeenCalledOnceWith();
    });
    });


    When I do this, it complains about a service downstream from the UserService not properly being provided with some data. So this means it's actually executing the code in my UserService as well as everything insjected into it. Why?

    I have written Angular tests in the past on other projects, and I have compared my code. I don't think I'm actually doing anything different. Does Angular not automatically provide mocks for things inject into a test? Am I supposed to do something like spyOn(injectedUserSvc, 'init').and.callFake(() => {}) instead to to test if it's being called or not?

    Continue reading...

Compartilhe esta Página