Skip to content

feat(core/testing): support directives option in TestBed.createComponent #68779

@chintankavathia

Description

@chintankavathia

Which @angular/* package(s) are relevant/related to the feature request?

No response

Description

Motivation

When testing custom form controls (components implementing ControlValueAccessor), there's currently no ergonomic way to apply formControl or other directives to the host component in a test. You're forced to create a wrapper test-host component just to use the directive in a template:

// Current workaround: boilerplate wrapper component
@Component({
  template: `<my-datepicker [formControl]="control"></my-datepicker>`,
  imports: [ReactiveFormsModule, MyDatepickerComponent],
})
class TestHost {
  control = new FormControl('2024-01-01');
}

const fixture = TestBed.createComponent(TestHost);

With the proposed change, this becomes:

const control = new FormControl('2024-01-01');
const fixture = TestBed.createComponent(MyDatepickerComponent, {
  directives: [
    { type: NgControl, bindings: [inputBinding('formControl', () => control)] }
  ],
});

This eliminates the wrapper component entirely and makes the test more focused and readable.

Current Behavior

TestBed.createComponent has no way to apply directives to the created component's host element. Testing custom form controls (or any component that expects a host directive) requires a boilerplate wrapper component.

Expected Behavior

TestBed.createComponent accepts a directives option and applies the specified directives to the component, consistent with ViewContainerRef.createComponent.

Proposed solution

ViewContainerRef.createComponent already supports a directives option. Add the same option to TestComponentOptions:

export interface TestComponentOptions {
  bindings?: Binding[];
  directives?: (Type<unknown> | DirectiveWithBindings<unknown>)[];
  inferTagName?: boolean;
}

Alternatives considered

Use wrapper component

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: testingIssues related to Angular testing features, such as TestBedfeatureLabel used to distinguish feature request from other issues

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions