【问题标题】:Angular 2(4) component with ControlValueAccessor testing带有 ControlValueAccessor 测试的 Angular 2(4) 组件
【发布时间】:2017-11-19 00:01:38
【问题描述】:

我想测试实现 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 中的通常输入 Input() 值等于 1(这是真的),并且 ngModel 值将等于 2,但是 ngModel = undefined 并且在调试之后我知道 ControlValueAccessor writeValue 方法不会在测试中调用环境(但它适用于浏览器)。那么我该如何解决呢?

【问题讨论】:

标签: angular jasmine karma-jasmine angular2-testing


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你必须用异步包裹你的测试,然后等待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);        
       }); 
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 2017-02-27
      • 2019-01-22
      • 2018-10-07
      • 2021-09-29
      • 2017-12-01
      • 1970-01-01
      • 2017-11-23
      • 2018-01-01
      相关资源
      最近更新 更多