2

Under my component , i ve this variable which take reference for the html widget element (which i got from a 3rd library):

<dx-data-grid id="myWidget" #myWidget>
   ...
</dx-data-grid>

So in my ts file i call it this way :

  @ViewChild('myWidget') datatableWidget: DxDataGridComponent;

And in some method , i using it this way

myMethod(){
  this.datatableWidget.instance.myWidgetMethod();
}

Now in my test file , i want to test my method : myMethod()

and as i m calling some private methode of my widget component , i got

 Cannot read property 'myWidgetMethod' of undefined 

How may i get reference of @ViewChild from my fixture , or how may i mock it or event spyOn It ??

Suggestions ?

firasKoubaa
  • 6,439
  • 25
  • 79
  • 148
  • in order to reference an element from template as `@ViewChild('myWidget')` the element must be declared as a [template reference variable](https://angular.io/guide/template-syntax#template-reference-variables-var) `` should be `` – ysf Jun 24 '19 at 14:22
  • @ysf it s done like you say , but how to use '@ViewChild' in spec files – firasKoubaa Jun 24 '19 at 14:32
  • 1
    it should work as it is. if it's not working, there must be a different problem. for that please provide more details about your test. – ysf Jun 24 '19 at 14:37
  • https://stackoverflow.com/a/51515877/4399281 – Fateh Mohamed Jun 24 '19 at 16:03
  • @firasKoubaa can u share your spec, component & html file. I hope you are doing `fixture.detectChanges()`. The error says that `this.datatableWidget.instance` is undefined. Also, I think you can directly access as `this.datatableWidget.myWidgetMethod()` as well. – Shashank Vivek Jun 25 '19 at 05:18
  • Can you post your test file? It might be related to where you placed the fixture. Inside beforeEach or fakeAsync or something similar. Also, have a look at this one: https://stackoverflow.com/questions/60984483/why-does-testing-with-template-driven-return-undefined-value?noredirect=1#comment107893628_60984483 – John Apr 07 '20 at 01:33

0 Answers0