测试从HTML输入元素获取价值的函数的最佳方法?

时间:2019-03-05 13:20:45

标签: javascript html angular typescript unit-testing

我正在尝试测试将输入元素的值分配给局部变量的函数,但是我仍然收到类型错误:

  

无法读取未定义的属性'nativeElement'

请查看我的stackblitz作为实时示例

html

<input #timeInput type="text" [value]="myData">
<button (click)="doSomething()">Click</button>

ts

 myData = 'initial text';

  @ViewChild('timeInput') tI: any;

  doSomething() {
    this.myData = this.tI.nativeElement.value;
  }

测试

  it('should', () => {
    component.something.nativeElement.value = 'new data';
    component.myFunc();
    expect(component.myData).toEqual('new data');
  })

1 个答案:

答案 0 :(得分:0)

通过查看this question,我似乎想出了一个可行的版本:

describe('component: TestComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [ AppComponent ]
    });
  });

  it('should be ok', () => {
    let fixture = TestBed.createComponent(AppComponent);
    let component = fixture.componentInstance;

    fixture.detectChanges();

    let input = fixture.debugElement.query(By.css('#myInput'));
    let el = input.nativeElement;

    expect(el.value).toBe('initial text');

    el.value = 'new data';

    component.doSomething();
    fixture.detectChanges();

    expect(component.myData).toBe('new data');

  });
});