Skip to content

Dependency injection with @Self() is broken in tests #31632

@jonrimmer

Description

@jonrimmer

🐞 bug report

Affected Package

@angular/core

Is this a regression?

Unknown

Description

The @Self() decorator does not work in tests to inject dependencies from directives placed on a component by a test-specific wrapper component.

E.g. if a I have a custom form control that injects NgControl using the @Self() decorator, as recommended by the Angular team:

constructor(@Self() ngControl: NgControl) {
  ngControl.valueAccessor = this;
}

And I try to use this in a test wrapper component:

@Component({
  template: `
    <form>
      <app-hello [formControl]="ctrl" name="test"></app-hello>
   </form>
 `
})
class TestWrapper {
  ctrl = new FormControl(''); 
}

describe('HelloComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, ReactiveFormsModule],
      declarations: [
        HelloComponent,
        TestWrapperComponent
      ],
    }).compileComponents();
  }));
});

Then test will fail due to an inability to inject NgControl.

🔬 Minimal Reproduction

https://github.com/jonrimmer/di-is-broken

If you run the app, you will see that it works fine.

If you run the test, you will see that it fails due to an inability to inject NgControl into the custom form control.

🔥 Exception or Error


Chrome 75.0.3770 (Mac OS X 10.14.5) HelloComponent should create FAILED
	No provider for NgControl ("[ERROR ->]"): @0:0
	error properties: Object({ ngSyntaxError: true, ngParseErrors: [ No provider for NgControl ("[ERROR ->]"): @0:0 ] })

🌍 Your Environment

Angular Version:





Angular CLI: 8.0.6
Node: 12.4.0
OS: darwin x64
Angular: 8.0.3
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.6
@angular-devkit/build-angular     0.800.6
@angular-devkit/build-optimizer   0.800.6
@angular-devkit/build-webpack     0.800.6
@angular-devkit/core              8.0.6
@angular-devkit/schematics        8.0.6
@angular/cli                      8.0.6
@ngtools/webpack                  8.0.6
@schematics/angular               8.0.6
@schematics/update                0.800.6
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.30.0

Anything else relevant?

Metadata

Metadata

Assignees

No one assigned

    Labels

    P5The team acknowledges the request but does not plan to address it, it remains open for discussionarea: compilerIssues related to `ngc`, Angular's template compilerarea: coreIssues related to the framework runtimefreq1: lowstate: confirmedtype: bug/fix

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions