2
我有jquery自動完成方法在angular2中使用,它調用服務從api獲取數據。 這裏是myComponent.ts:Angular2 + jquery自動完成組件:無法調用組件內的spec文件
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>
我發現,因爲它是混合角與jquery很難測試的代碼(這是不我知道的很好)。但現在,我想從我的測試文件中調用method1,method2,mainMethod,anotherMethod來獲得更多的代碼覆蓋率。
myComponent.spec.ts文件:
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.
甚至調用方法1和method2,我不能嘲笑this.myVar在規範呢?我應該如何去測試各種方法?
你說的模擬'this.myVar'你是什麼意思嘗試去完成? –
'this.myVar'存儲jQuery對象並在spec文件中調用'method1'時,它說找不到'.val()'的undefined。所以'this.myVar'不會被嘲笑 – candidJ
嘲笑什麼?你爲什麼期望它被嘲笑? –