I have jquery autocomplete method being used inside angular2 which calls service to fetch data from api. Here is myComponent.ts :
export class myComponent {
private myVar;
private binding1;
private binding2;
constructor( @Inject(ElementRef) private elementRef: ElementRef,private _myService: MyService) {
}
public method1() { return this.myVar.val().toUpperCase(); }
public method2() { return this.myVar.val(""); }
private ngOnInit() {
var _this = this;
this.myVar = $(this.elementRef.nativeElement).children().eq(0).autocomplete({
source: function(request,callback){
_this.mainMethod(request,callback);
},
delay:0,
select: (event, ui) => {
// …},
open: function(e,ui)
{
//…
},
appendTo: $('body')
});
//renderMethod add data to the view using $().append()
public mainMethod (res, callback) { //gets called from inside autocomplete
if(condition 1) {
//renders data from service by calling methodOnService()
//returns binding1 and binding2 which gets rendered in view (see html)
}
else {
//call anotherMethod();
//sets binding1 and binding2 which gets rendered in view (see html)
}
}
public anotherMethod() {
//…
}
myComponent.html:
<input type="text" value="{{binding1}}" size="{{binding2}}" maxlength="94"><span></span>
I’m finding it hard to test the code since it is mixing angular with jquery (which is not good I know). But right now, I want to call method1, method2, mainMethod, anotherMethod from my test file to get more code coverage.
myComponent.spec.ts file :
fit(‘my component test file’,inject([TestComponentBuilder, MyComponent, ElementRef], (tcb:TestComponentBuilder) => {
tcb.createAsync(MyComponent)
.then((fixture) => {
const element = fixture.debugElement.nativeElement;
const instance = fixture.componentInstance;
console.log("component instance", fixture.componentInstance);
fixture.componentInstance.binding2 =12;
fixture.componentInstance.binding1 = 'aapl';
spyOn(instance, "methodOnService");
spyOn(instance,"anotherMethod");
fixture.detectChanges(); //while debugging, it invokes 'ngOnInit' method but doesn't invoke autocomplete method
fixture.componentInstance.symbol= 'aa';
fixture.componentInstance.binding2 =12;
fixture.detectChanges(); //it doesn't even invoke 'ngOnInit'
expect(instance.methodOnService.calls.any()).toEqual(true); //error : Expected false to equal true
expect(instance.anotherMethod).toHaveBeenCalled();
// error :Expected spy anotherMethod to have been called.
Even For calling method1 and method2, I'm unable to mock this.myVar in spec ? how should i go about testing various method ?