0

Is it possible to use a base class for the unit tests in angular? Because a lot of my imports and declarations are always the same. If i add or replace a class, i always have to change the imports and declarations in every test class.

    beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [DialogModule, DynamicDialogModule, FormsModule, TableModule, HttpClientTestingModule, ContextMenuModule],
        declarations: [MyDialog ,OtherDialog],
        providers: [MyService],
    })
        .compileComponents();
}));

The above code ist the code which is mostly the same in every test class, so this is the code that should be in the base class.

pmueller
  • 143
  • 1
  • 19

2 Answers2

1

Well yes, it's possible. You can put

export const configureTestBed = () => TestBed.configureTestingModule({
        imports: [DialogModule, DynamicDialogModule, FormsModule, TableModule, HttpClientTestingModule, ContextMenuModule],
        declarations: [MyDialog ,OtherDialog],
        providers: [MyService],
    }).compileComponents();

in an exported function call it in each beforeEach (or something of that like).

However, I do not recommend this. Whenever you're unit testing, you should only import, declare, provide what is needed for what you are unit testing.

If you import, declare, provide a bunch of stuff that a component, service, directive does not need, you can create headaches for yourself AND it will make the tests run slower. I am speaking from experience about this.

This is a very good exchange for you to read What does “DAMP not DRY” mean when talking about unit tests?. Also, don't take it lightly, it's okay if you have some repeated code from test to test. This will give you greater flexibility and control.

AliF50
  • 16,947
  • 1
  • 21
  • 37
0

You can chuck it all in a TestingModule

@NgModule({
  imports: [
    DialogModule, 
    DynamicDialogModule, 
    FormsModule, 
    TableModule, 
    HttpClientTestingModule, 
    ContextMenuModule
  ],
  declarations: [
    MyDialog,
    OtherDialog
  ],
  providers: [MyService]
})
export class TestingModule { }

Then in all your tests you can just import this module:

beforeEach(async(() => {
  TestBed.configureTestingModule({ imports: [TestingModule] });
}))
Vedran
  • 10,369
  • 5
  • 50
  • 57