How to reuse all imports in Angular test files

前端 未结 2 1975
情歌与酒
情歌与酒 2020-12-18 03:38

Lets say I have a simple module AppModule which has many imports, declarations and providers. Now I want to write a test for a component ListComponent

2条回答
  •  一生所求
    2020-12-18 04:08

    You can create reusable const that contains the commom imports, providers from the modules you want.

    for example in a app.providers.ts file you can have your providers like this:

    import service1 from '.path/service/service1';
    import service2 from '.path/service/service2';
    
    export const providers = [service1, service2 ];
    

    and for your imports in a app.imports.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { AppRoutingModule } from './app-routing.module';
    import { Module1} from ''.path/service/module1';
    
    export const imports= [
        BrowserModule,
        AppRoutingModule,
        Module1
    ],
    

    and on your app.module.ts and any other module you wanna use the same imports and providers you can do:

    import { providers } from './app.providers';
    import { imports } from './app.imports';
    @NgModule({
        declarations: [AppComponent],
        imports: imports,
        providers: providers,
        bootstrap: [AppComponent]
    })
    

    You can also use the spread operator to add your unique imports to these shared imports on a specific module.

提交回复
热议问题