【问题标题】:Jasmine: Testing a function returning a promiseJasmine:测试返回承诺的函数
【发布时间】: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.isUniquemyFunction() 的调用,但它仍然显示未覆盖。不知道为什么。

如果您发现任何其他问题,请告诉我,因为我对 Angular 和 Jasmine 还很陌生。谢谢。

【问题讨论】:

    标签: angularjs testing typescript jasmine


    【解决方案1】:

    您需要致电$scope.$digest() 以使您的承诺在您的测试中得到解决。有一个方便的教程可以深入讨论这个问题here

    希望有帮助!

    【讨论】:

    • 我在想承诺已经解决了,这就是为什么它给了我正确的唯一性结果并且测试通过了。让我读一下这个。谢谢。
    • 很容易测试你的承诺解决理论 - 只需在你的 then() 中添加一个 console.log() ,看看它是否在你的测试中被击中 :)
    • 这里有一篇更深入的 Angular 1.x 文章(同样的原则仍然适用):bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q
    • 这很有帮助,但仍然没有回答我的任何问题。
    • 就在expect(unique).toEqual(false); 之前放置一个console.log - 如果在您的测试运行时打印到您的屏幕上,这将快速验证您的承诺已在您的测试中得到解决。
    猜你喜欢
    • 2014-10-31
    • 2020-07-30
    • 2016-12-18
    • 2016-06-17
    • 2014-05-19
    • 2020-04-07
    • 2018-07-27
    • 2015-03-05
    • 2017-05-26
    相关资源
    最近更新 更多