使用ControlValueAccessor测试Angular 2(4)组件

8

我想测试一个组件,该组件实现了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();
  }));
});

所以,我期望在我的自定义组件中usualInput Input()的值等于1(这是正确的),而ngModel的值应该等于2,但是ngModel = undefined。经过调试,我知道在测试环境中ControlValueAccessor的writeValue方法没有被调用(但在浏览器中它能正常工作)。那么我该如何解决呢?


你能提供你的“自定义组件”的源代码吗? - shohrukh
2个回答

1

在您的ControlValueAccessor组件中,如果没有注入并避免循环依赖,则无法访问ngModel

ControlValueAccessor有一个writeValue方法,它在控件更新时接收值 - 如果需要,您可以将此值存储在组件中,然后进行测试。


1

你需要在测试中使用async进行包装,并等待 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);        
   }); 
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接