【发布时间】:2017-04-07 16:42:35
【问题描述】:
我正在为我的 Angular 应用程序使用 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 还很陌生。谢谢。
【问题讨论】:
标签: angularjs testing typescript jasmine