Performance: TestBed configuration
TestBed configuration affects the speed of running Angular unit tests and the responsiveness of test suites during development.
Jump into concepts and practice - no test required
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [CommonModule],
providers: []
}).compileComponents();
});beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent, UnusedComponent, AnotherUnusedComponent],
imports: [CommonModule, FormsModule, HttpClientModule],
providers: [SomeService]
}).compileComponents();
});| Pattern | Declarations/Imports | Compilation Time | Memory Usage | Verdict |
|---|---|---|---|---|
| Heavy TestBed Setup | Many unused components and modules | High (200-500ms) | High | [X] Bad |
| Minimal TestBed Setup | Only required components and modules | Low (50-150ms) | Low | [OK] Good |
TestBed in unit testing?declarations in the configuration.declarations with the component. Others misuse imports, providers, or bootstrap.fixture.componentInstance.title output?TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
// MyComponent code:
// title = 'Hello Test';title is set.TestBed.configureTestingModule({
declarations: [MyComponent]
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();compileComponents() must be called to compile templates asynchronously.compileComponents() before creating the component, which can cause errors.providers array. To mock a service, use provide with useValue.