-2

I am attempting to test my function that takes the value of an input element and assigns it to local variable, however I keep receiving type error:

Cannot read property 'nativeElement' of undefined

Please see my stackblitz for live example

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;
  }

test

  it('should', () => {
    component.something.nativeElement.value = 'new data';
    component.myFunc();
    expect(component.myData).toEqual('new data');
  })
physicsboy
  • 5,656
  • 17
  • 70
  • 119

1 Answers1

0

I seem to have come up with a working version by seeing 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');

  });
});
physicsboy
  • 5,656
  • 17
  • 70
  • 119