Search code examples
angulardependency-injectionjestjsangular-spectatorspectator

Global import of modules with Jest and Spectator


In my Angular project, I have removed Karma in order to use Jest.js with Spectator instead. It works well, but now, as the module related to translations is a bit verbose, I am trying to import it globally. I read in the documentation of Spectator this can be done in test.js, but unless I am mistaken, that file is used by Karma, not by Jest.js. So I would like to know if it is possible to do global injections with Jest/Spectator, thanks!


Solution

  • For those using Jest, the global injections should be set in setupJest.ts

    Example:

    import 'jest-preset-angular/setup-jest';
    
    import { defineGlobalsInjections } from '@ngneat/spectator';
    import { HttpClient, HttpClientModule } from '@angular/common/http';
    import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    
    export function HttpLoaderFactory(http: HttpClient) {
        return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }
    
    defineGlobalsInjections({
        imports: [
            HttpClientModule,
            TranslateModule.forRoot({
                loader: {
                    provide: TranslateLoader,
                    useFactory: HttpLoaderFactory,
                    deps: [HttpClient]
                }
            })
        ]
    });