- 首先我们需要自定义一个组件,如下:
@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'); });
网友评论