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

时间:2018-07-31 16:34:54

标签: angular unit-testing

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

在组件中

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

ngOnInit(): void {
    this.ngControl.valueChanges

在单元测试中

beforeEach(() => {
      fixture = TestBed.createComponent(component);
      fixture.detectChanges();

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

4 个答案:

答案 0 :(得分:4)

适用于:

beforeEach(() => {
     fixture = TestBed.createComponent(сomponent);
     (fixture.componentInstance as any).ngControl = new FormControl();

答案 1 :(得分:2)

我通过覆盖

解决了这个问题
    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();
  });

答案 2 :(得分:0)

我只是遇到了同样的问题,并为NgControl使用了一个模拟对象来解决它。

定义模拟对象...

let formControlSpy: jasmine.SpyObj<NgControl>;
formControlSpy = jasmine.createSpyObj('NgControl', ['value']);

提供用于组件注入的模拟...

TestBed.configureTestingModule({
    providers: [
        TestComponent,
        { provide: NgControl, useValue: formControlSpy }
    ]
});

injector = getTestBed();
component = injector.get(PasswordFormControlComponent);

然后配置控件的所需值...

beforeEach(() => formControlSpy.value.and.returnValue('value'));

答案 3 :(得分:0)

取决于您要对控件执行的操作,如果您只想解决错误,则可以提供NgControl,如下所示:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        ...
        providers: [
            { provide: NgControl, useValue: new FormControl() },
        ]
        ...
    })
    .compileComponents()
}))