TestBed helps you set up and test Angular components and services easily. It creates a small Angular environment for your tests.
TestBed configuration in Angular
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Angular
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [MyModule],
providers: [MyService]
}).compileComponents();declarations is for components, directives, and pipes you want to test.
imports is for Angular modules your component depends on.
Examples
Angular
TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();Angular
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [FormsModule]
}).compileComponents();Angular
TestBed.configureTestingModule({
providers: [MyService]
});Sample Program
This test sets up TestBed with a simple component. It checks if the component creates and shows the correct text.
Angular
import { TestBed } from '@angular/core/testing'; import { Component } from '@angular/core'; @Component({ selector: 'app-hello', template: '<h1>Hello {{name}}</h1>' }) class HelloComponent { name = 'Angular'; } describe('HelloComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [HelloComponent] }).compileComponents(); }); it('should create the component and display name', () => { const fixture = TestBed.createComponent(HelloComponent); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toBe('Hello Angular'); }); });
Important Notes
Always call compileComponents() when testing components to compile templates.
You can add imports to include Angular modules your component needs.
Use providers to add services or mocks for dependency injection.
Summary
TestBed configures a mini Angular environment for testing.
Use declarations, imports, and providers to set up what your test needs.
Call compileComponents() to prepare components before testing.
Practice
1. What is the main purpose of Angular's
TestBed in unit testing?easy
Solution
Step 1: Understand TestBed's role
TestBed sets up a lightweight Angular environment to test parts of your app without running the full app.Step 2: Compare options
Only To create a small Angular environment for testing components and services describes this testing environment purpose. Others describe unrelated tasks.Final Answer:
To create a small Angular environment for testing components and services -> Option AQuick Check:
TestBed purpose = create test environment [OK]
Hint: TestBed sets up Angular test environment, not full app build [OK]
Common Mistakes:
- Confusing TestBed with production build tools
- Thinking TestBed generates templates automatically
- Assuming TestBed replaces Angular modules
2. Which of the following is the correct way to declare a component in TestBed configuration?
easy
Solution
Step 1: Identify where components go in TestBed
Components must be listed underdeclarationsin the configuration.Step 2: Check each option
Only TestBed.configureTestingModule({ declarations: [MyComponent] }) usesdeclarationswith the component. Others misuseimports,providers, orbootstrap.Final Answer:
TestBed.configureTestingModule({ declarations: [MyComponent] }) -> Option DQuick Check:
Components go in declarations [OK]
Hint: Components go in declarations, modules in imports, services in providers [OK]
Common Mistakes:
- Putting components inside imports or providers
- Using bootstrap in TestBed config (only for app modules)
- Forgetting to declare components causes errors
3. Given this TestBed setup, what will
fixture.componentInstance.title output?TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
// MyComponent code:
// title = 'Hello Test';medium
Solution
Step 1: Confirm component declaration and compilation
MyComponent is declared and compiled, so it can be created and used.Step 2: Understand fixture and detectChanges
Creating fixture and calling detectChanges initializes component and bindings, sotitleis set.Final Answer:
'Hello Test' -> Option BQuick Check:
Declared + compiled + detectChanges = property accessible [OK]
Hint: Declare and compile components before accessing properties [OK]
Common Mistakes:
- Forgetting to call compileComponents causes errors
- Not calling detectChanges leaves properties uninitialized
- Assuming properties are undefined without initialization
4. What is the error in this TestBed setup?
TestBed.configureTestingModule({
declarations: [MyComponent]
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();medium
Solution
Step 1: Check TestBed configuration steps
When testing components with templates,compileComponents()must be called to compile templates asynchronously.Step 2: Identify missing step
The code missescompileComponents()before creating the component, which can cause errors.Final Answer:
Missing call to compileComponents() before createComponent() -> Option CQuick Check:
compileComponents() required before createComponent() [OK]
Hint: Always call compileComponents() before createComponent() for templates [OK]
Common Mistakes:
- Skipping compileComponents() causes template errors
- Putting components in imports instead of declarations
- Calling detectChanges() too early
5. You want to test a component that uses a service injected via constructor. Which TestBed configuration is correct to provide the service mock?
hard
Solution
Step 1: Understand service injection in TestBed
Services are provided viaprovidersarray. To mock a service, useprovidewithuseValue.Step 2: Analyze options
TestBed.configureTestingModule({ declarations: [MyComponent], providers: [{ provide: MyService, useValue: mockService }] }) correctly provides a mock service. TestBed.configureTestingModule({ declarations: [MyComponent], imports: [MyService] }) wrongly puts service in imports. TestBed.configureTestingModule({ declarations: [MyComponent], declarations: [MyService] }) wrongly declares service as component. TestBed.configureTestingModule({ providers: [MyComponent, MyService] }) wrongly provides component as service.Final Answer:
TestBed.configureTestingModule({ declarations: [MyComponent], providers: [{ provide: MyService, useValue: mockService }] }) -> Option AQuick Check:
Mock services go in providers with provide/useValue [OK]
Hint: Use providers with provide and useValue for service mocks [OK]
Common Mistakes:
- Putting services in imports or declarations
- Providing components instead of services
- Not mocking services causing real calls
