1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Mock provided service in Standalone component in Jest unit test

Discussão em 'Angular' iniciado por Cody Pritchard, Outubro 9, 2024 às 16:22.

  1. I have a service that is not provided in root, instead it is provided in my component like so:

    @Injectable()
    export class NavbarFacadeService extends AbstractStateFacade<IDrawerState, DrawerStateActions> implements OnDestroy {
    ...
    }


    @Component({
    selector: 'navbar-drawer',
    standalone: true,
    imports: [],
    providers: [NavbarFacadeService],
    template: `
    ...
    `,
    changeDetection: ChangeDetectionStrategy.OnPush,
    })
    export class NavbarDrawerComponent implements AfterViewInit {
    ...
    }


    The reason for providing it in the component vs making it provided in root, is because I want the service to be cleaned up automatically when the component is destroyed. This is working fine. The issue is unit testing this.

    In my unit test, i should be able to mock the instance of the NavbarFacadeService like so:

    const mockNavbarFacadeService = MockService(NavbarFacadeService, {
    ...
    });

    beforeEach(async () => {
    await TestBed.configureTestingModule({
    imports: [NavbarDrawerComponent],
    providers: [
    { provide: NavbarFacadeService, useValue: mockNavbarFacadeService },
    ]
    }).compileComponents();

    fixture = TestBed.createComponent(NavbarDrawerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    });


    However, when provided in this way, when the unit tests run, the service is not of a mocked instance but instead the actual provided instance and is executing real functions instead of the ones i mocked.

    Yet, if I remove the provider from the component, and go back to making the service provided in root then it correctly gets the mocked instance.

    So, when working with standalone components that provide a service, is there some other way of setting up the TestBed to provide the mocked value that I am just not aware of?

    Continue reading...

Compartilhe esta Página