繁体   English   中英

带有 ControlValueAccessor 测试的 Angular 2(4) 组件

[英]Angular 2(4) component with ControlValueAccessor testing

我想测试实现 ControlValueAccessor 接口的组件,以允许在我的自定义组件中使用[(ngModel)] ,但问题是通常的输入正确但ngModel - undefined 这是代码示例:

@Component({
  template: `
    <custom-component
      [usualInput]="usualInput"
      [(ngModel)]="modelValue"
    ></custom-component>`
})

class TestHostComponent {
  usualInput: number = 1;
  modelValue: number = 2;
}

describe('Component test', () => {
  let component: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;
  let de: DebugElement;
  let customComponent: DebugElement;

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

所以,我希望 customComponent 中的 commonInput Input() 值等于 1(这是真的),ngModel 值等于 2,但是 ngModel = undefined 并且在调试之后我知道 ControlValueAccessor writeValue 方法不会在测试环境中调用(但是它适用于浏览器)。 那么我该如何解决呢?

在您的ControlValueAccessor组件中,您无权访问ngModel除非您注入它并做了一些技巧来避免循环依赖。

ControlValueAccessor具有writeValue方法,该方法在更新时从控件接收值——如果需要,您可以将此值存储在您的组件中,然后对其进行测试。

你必须用异步包装你的测试,并等待fixture.whenStable

 it('should get ngModel', async(() => { let customComponent = debugEl.query(By.directive(CustomComponent)); fixture.whenStable().then(() => { fixture.detectChanges(); expect(customComponent.componentInstance.value).toEqual(2); }); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM