美文网首页
formItem双向绑定的单元测试

formItem双向绑定的单元测试

作者: 紫诺_qiu | 来源:发表于2017-01-01 23:59 被阅读30次
    • 首先我们需要自定义一个组件,如下:
    @Component({
      selector: 'sion-basic-select', 
      template: `
      <sino-remote-select [formControl]="control" 
      </sino-remote-select>`,
    })
    class BasicSelectComponent {
      control = new FormControl();
    
      @ViewChild(SinoRemoteSelectComponent) select: SinoRemoteSelectComponent;
    }
    
    • 然后我们可以模拟做单元测试前的初始化

      import { Component, ViewChild } from '@angular/core';
      import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
      import { FormControl } from '@angular/forms';
      
      import { SinoRemoteSelectComponent } from './sino-remote-select.component';
      import { SinoRemoteSelectComponent } from './sino-remote-select.component';
      
      describe('sino-remote-select: form item features', () => {
        let fixture: ComponentFixture<BasicSelectComponent>;
        let basicSelectComponent: BasicSelectComponent;
      
        beforeEach(() => {
          TestUtils.beforeEachCompiler([SinoRemoteSelectComponent, BasicSelectComponent]);
        });
      
        beforeEach(() => {
          fixture = TestBed.createComponent(BasicSelectComponent);
          basicSelectComponent = fixture.componentInstance;
        });
      
    • 现在,我们先要测试当模型值发生改变时,模板值是否与模板值相等

      it('can use sino-remote-select in reactive forms', () => {
          basicSelectComponent.control = new FormControl('02');  //给模型赋值
      
          fixture.detectChanges();
      
          expect(basicSelectComponent.select.value).toBe('02');  //期望模板值与模型值相等
        });
      
    • 对应的,我们需要测试当模板值改变时,模型值是否改变

      it('should update the form value when the view changes', () => {
          fixture.detectChanges();
      
          basicSelectComponent.select.value = '123';
          fixture.detectChanges();
      
          expect(basicSelectComponent.control.value).toBe('123');
        });
      

    相关文章

      网友评论

          本文标题: formItem双向绑定的单元测试

          本文链接:https://www.haomeiwen.com/subject/idtwvttx.html