如何从单元测试中访问注入的ngControl?

Vit*_*gon 5 unit-testing angular

如何从单元测试中访问注入的ngControl?如何解决错误?

在组件中

constructor(
    @Self() @Optional() public ngControl: NgControl
  ) { }

ngOnInit(): void {
    this.ngControl.valueChanges
Run Code Online (Sandbox Code Playgroud)

在单元测试中

beforeEach(() => {
      fixture = TestBed.createComponent(component);
      fixture.detectChanges();
Run Code Online (Sandbox Code Playgroud)

执行测试时得到错误 TypeError: Cannot read property 'valueChanges' of null

小智 12

我通过重写解决了这个问题

    beforeEach(async () => {
      const NG_CONTROL_PROVIDER = {
          provide: NgControl,
          useClass: class extends NgControl {
          control = new FormControl();
          viewToModelUpdate() {}
      },
    };

    await TestBed.configureTestingModule({
      declarations: [YourComponentName],
      imports: [FormsModule],
    })
      .overrideComponent(YourComponentName, {
        add: { providers: [NG_CONTROL_PROVIDER] },
      })
      .compileComponents();
  });
Run Code Online (Sandbox Code Playgroud)

  • 好的,这有效。您能详细说明一下为什么这是有效的吗?例如,为什么它不能使用`providers:[提供:NgControl,useValue:NG_CONTROL_PROVIDER}`。重写控制提供者有什么注意事项吗? (2认同)

Vit*_*gon 9

适用于:

beforeEach(() => {
     fixture = TestBed.createComponent(?omponent);
     (fixture.componentInstance as any).ngControl = new FormControl();
Run Code Online (Sandbox Code Playgroud)