Initializing service values before tests using Angular 21 and Vitest

Discussão em 'Angular' iniciado por Zachu, Novembro 26, 2025.

  1. Zachu

    Zachu Guest

    I've just moved over to Angular 21, and started using Vitest.

    I'd like to initialize one of my services before the tests starts.
    So I added provideAppInitializer in the test providers like so

    File: src/test-providers.ts
    ---
    // Imports

    const testProviders = [
    provideHttpClient(),
    provideHttpClientTesting(),
    provideLuxonDateAdapter(),
    provideAppInitializer(() => {
    const currentService = inject(CurrentService);
    currentService.setMe(mockMe());
    currentService.setCustomer(1, mockCustomer());
    }),
    ];

    export default testProviders;


    File: angular.json
    ---
    ...
    "test": {
    "builder": "@angular/build:unit-test",
    "options": {
    "include": ["src/app/**/*.spec.ts"],
    "providersFile": "src/test-providers.ts"
    }
    }
    ...


    But then I end up with the error

    ✘ [ERROR] File 'src\test-providers.ts' not found in TypeScript compilation. [plugin angular-compiler]

    I am also aware that there's something called setupFiles in angular.json, but I don't really know how to inject a service there.

    Does anyone know how to inject and run a service before test starts?

    Continue reading...

Compartilhe esta Página