【问题标题】:The best way in which to test a function that takes value from HTML input element?测试从 HTML 输入元素中获取值的函数的最佳方法是什么?
【发布时间】:2019-07-26 23:34:59
【问题描述】:

我正在尝试测试我的函数,该函数获取输入元素的值并将其分配给局部变量,但是我一直收到类型错误:

无法读取未定义的属性“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');
  })

【问题讨论】:

标签: javascript html angular typescript unit-testing


【解决方案1】:

看到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');

  });
});

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 2014-05-12
    • 2010-09-29
    • 2019-12-09
    • 2018-04-27
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多