angularjs - Jasmine:测试返回 promise 的函数

标签 angularjs testing typescript jasmine

我正在使用 Jasmine 为我的 Angular 应用程序编写测试。所有测试都通过了。我的类(class)如下所示:

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 返回一个 bool 值 promise 。 现在,我正在努力让我的测试达到 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 的新手。谢谢。

最佳答案

您需要调用 $scope.$digest() 以使您的 promise 在您的测试中解析。有一个方便的教程对此进行了深入讨论 here

希望对您有所帮助!

关于angularjs - Jasmine:测试返回 promise 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40768421/

相关文章:

java - 如果部分测试花费的时间太长,如何从 JUnit 测试返回到 main 方法

javascript - Mocha 将变量传递给下一个测试

testing - 如何从 "main()"测试 "go test"例程?

javascript - 使用 HttpClient 的模块是否应该在导入中声明 HttpClientModule?

angularjs - angular-ui ng-grid 如何使聚合行成为可编辑行

angularjs - 第一个服务总是以未知的形式出现

css - Angular6:如何为复选框添加边框颜色

typescript - Openlayers:LineString 上的渐变发光

javascript - 在包含模块的 Angular JS 文件中,函数和对象的顺序真的很重要吗?

javascript - 将 ng-click 事件添加到 angular-ui Accordion