Angular:如何设置浅层组件的ngModel?

问题描述 投票:1回答:1

假设我有一个组件InputComponent,它实现了ControlValueAccessor。现在,我有AnotherComponent,它像这样使用第一个组件:

<my-input [(ngModel)]="text"></my-input>

我正在尝试测试AnotherComponent,并且设置了NO_ERRORS_SCHEMA选项。在测试中,我需要在ngModel中添加一些值以模拟用户输入。

这是我尝试过的:

const input = fixture.debugElement.query(By.css('my-input'));
input.nativeElement.value = 'some string';
input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();

// then I assert that AnotherComponent `text` property is equal to the one I set to `ngModel`

但是text属性为空,我在做什么错?

P.S。根据要求添加了TestBed,但是该测试相当普遍。

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AnotherComponent ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AnotherComponent);
    fixture.detectChanges();
  });
angular unit-testing
1个回答
0
投票

为了使ngModel工作,您还需要在测试中导入FormsModule

TestBed.configureTestingModule({
  imports: [ FormsModule ],
  declarations: [ AnotherComponent ],
  schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
© www.soinside.com 2019 - 2024. All rights reserved.