【问题标题】:Getting 'NullInjectorError: No provider for NgControl!' when using custom control获取“NullInjectorError:NgControl 没有提供程序!”使用自定义控件时
【发布时间】:2021-11-28 06:57:45
【问题描述】:

我自定义了一个单选按钮。到目前为止它正在工作。但我注意到我的控制台中有提到的错误并且无法运行任何测试。这是一个常见错误,但到目前为止,SO 上的现有解决方案无法帮助我。

这是我的代码:

单选按钮.component.hmtl:

<input
  type="radio"
  data-test-id="radio-button"
  [attr.id]="id"
  [attr.name]="name"
  [ngClass]="{
    'radio-button': disabled === false,
    'radio-button-without-focus': disabled === true,
    'disabled-radio': disabled === true
  }"
  [value]="value"
  [checked]="checked"
  [disabled]="disabled"
  (change)="onChange($event)"
/>

radio-button.component.ts:

@Component({
  selector: 'fls-radio-button',
  templateUrl: './radio-button.component.html',
  styleUrls: ['./radio-button.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RadioButtonComponent),
      multi: true
    }
  ],
  encapsulation: ViewEncapsulation.None
})
export class RadioButtonComponent extends RadioControlValueAccessor {
  @HostBinding('class') classes = 'fls-radio-button';

  @Input() id: string;

  @Input() name: string;

  @Input() value: SimpleFieldValue;

  @Input() label: string;

  @Input() disabled = false;

  @Input() checked = false;

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}

radio-button.module.ts:

@NgModule({
  declarations: [RadioButtonComponent],
  exports: [RadioButtonComponent, FormsModule],
  imports: [CommonModule, SharedI18nModule, FormsModule, ReactiveFormsModule]
})
export class RadioButtonModule {}

单选按钮.component.spec.ts:

describe('RadioButtonComponent', () => {
  let component: RadioButtonComponent;
  let fixture: ComponentFixture<RadioButtonComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [RadioButtonComponent],
      imports: [CommonModule, ...getSharedI18nTestingModules(), FormsModule, ReactiveFormsModule]
    }).compileComponents();
  });

  const createComponent = () => {
    fixture = TestBed.createComponent(RadioButtonComponent);
    component = fixture.componentInstance;
    component.label = 'Copy';
    component.disabled = true;
    fixture.detectChanges();
  };

  it('Should create', () => {
    createComponent();
    expect(component).toBeTruthy();
  });
});

我到处都导入了 FormsModule 和 ReactiveFormsModule。有谁知道我是否遗漏了什么?

【问题讨论】:

    标签: html angular typescript unit-testing testing


    【解决方案1】:

    在后台NG_VALUE_ACCESSOR 正在向注射器询问NgControl,并将控件的valueAccessor 属性设置为NG_VALUE_ACCESSOR 中提供的值。所以我想你需要在你的测试中提供NgControl

    【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2019-01-29
    • 1970-01-01
    • 2016-11-21
    • 2021-03-14
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多