1
我正在使用Jasmine編寫測試以用於我的角度應用程序。所有的測試都通過了。我的類看起來如下:Jasmine:測試返回承諾的函數
class xyz implements ng.IComponentController {
private myList: ng.IPromise<MyList[]> ;
//declare necessary variables
/* @ngInject */
constructor(private ListService: ListService,
) {
this.myList = this.ListService.getList();
}
public onChange(): void {
this.isNameUnique(this.name).then(function(unique){
scope.isUnique = unique;
scope.errorNameInput = !reg.test(scope.name) || !scope.isUnique;
scope.myFunction({
//do something
});
});
}
public isNameUnique(name: string): ng.IPromise<boolean> {
return this.myList
.then(
(names) => {
_.mapValues(names, function(name){
return name.uuid.toLowerCase();
});
return (_.findIndex(names, { uuid : uuid.toLowerCase() }) === -1) ? true : false;
});
}
}
在這裏,我使用ListService預填充我在構造函數本身名單(所以它調用該服務僅一次)。然後,在我的onChange方法中,如果名稱是唯一的,我檢查 。 isNameUnique返回一個布爾值的承諾。 現在,我試圖讓我的測試100%覆蓋。我對這裏測試isNameUnique方法感到困惑。我的第一個考驗就是:
(假設myList中類似反應的JSON,我會從服務中獲得)
this.$scope.myFunction = jasmine.createSpy('myFunction');
it('should ...', function() {
this.view.find(NAME_INPUT).val('blue').change(); // my view element.
this.getList.resolve(myList);
this.controller.isNameUnique('blue').then(function (unique) {
expect(unique).toEqual(false); //since blue is already in my json
expect(this.controller.errorNameInput).toEqual(true); //since its not unique, errornameinput will be set to true
expect(this.$scope.myFunction).toHaveBeenCalled();
});
});
我希望這個測試覆蓋線:scope.errorNameInput = !reg.test(scope.name) || !scope.isUnique
和調用的myFunction()
,但它仍然顯示裸露。不知道爲什麼。
請讓我知道,如果你看到任何錯誤,因爲我是Angular和Jasmine的新手。謝謝。
我在想這個承諾已經解決了,這就是爲什麼它給了我唯一性的正確結果,並且測試正在通過。讓我看看這個。謝謝。 –
這很容易測試你的承諾理論解決 - 只需在你的'then()'中查找'console.log()',看看它是否在你的測試中被擊中:) –
這裏是一個更深入的文章Angular 1.x(同樣的原則仍然適用):http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/ –