createComponent creates an Angular component instance. Its role depends on context: ViewContainerRef can use it to select a component programmatically, while TestBed uses it to instantiate a component for unit tests. section 29.4.1 section 16.2.2
Use createComponent in two distinct situations:
- Call TestBed.createComponent(SimpleComponent) after configuring the testing module. The result is a ComponentFixture, and its componentInstance property exposes the created component. section 29.4.1
- Call ViewContainerRef.createComponent to select a component programmatically instead of declaring a fixed element in a template. section 16.2.2
- Treat dynamic component creation cautiously because the discussed approach is described as limited and potentially more troublesome than useful. section 16.2.2
Creating a component for a unit test
Configure the test module inside beforeEach, declare SimpleComponent, and create the fixture there: fixture = TestBed.createComponent(SimpleComponent); component = fixture.componentInstance;. A basic test can then verify that component is defined. The fixture also provides debugElement, nativeElement, detectChanges(), and whenStable() for further testing.
