javascript - Jasmine : Timeout - Async callback was not invoked within timeout

标签 javascript angularjs unit-testing karma-jasmine

我需要测试一个从 url 加载图像的 AngularJs 服务。这是我的服务:

/*global angular, Image*/
(function () {
  'use strict';
  function SourceLoader($q, $log) {

    /**
     * Load an image from url and return a promise which is resolved when image is loading is done.
     * It return the images object as resolved promise.
     * @param url source of the image
     * @returns {Promise} unresolved promise of image.
     */
    function loadImage(url) {
      var deferred = $q.defer(),
          image = new Image();
      image.onload = function () {
        deferred.resolve(image);
      };
      image.onerror = function (error) {
        $log.error('Error while loading image from url ' + url);
        $log.debug(error);
        deferred.reject(error);
      };
      image.src = url;
      return deferred.promise;
    }

    /**
     * Load images from and array of urls nd return the array of loaded images. The order of returned
     * images is same as the order of passed urls.
     * @param urls sources if images in array.
     * @returns {Promise} unresolved promise.
     */
    function loadImages(urls) {
      var count = 0, deferred = $q.defer(),
          images = [],
          callback = function (image, index) {
            images.insert(index, image);
            count += 1;
            if (count === urls.length) {
              //All images are loaded. High time to resolve promise.
              deferred.resolve(images);
            }
          };
      urls.forEach(function (url, index) {
        var image = new Image();
        image.onload = function () {
          callback(image, index);
        };
        image.onerror = function (event) {
          $log.error('Error while loading image from url ' + url);
          $log.debug(event);
          callback(event, index);
        };
        image.src = url;
      });
      return deferred.promise;
    }

    return {
      loadImage: loadImage,
      loadImages: loadImages
    };
  }

  var app = angular.module('myCanvasModule'),
      requires = [
        '$q',
        '$log',
        SourceLoader
      ];
  app.factory('SourceLoaderService', requires);
}());

我将 Karma 与 Jasmine 一起用于测试服。我的测试服是这样的:

/*global describe, TestUtils, beforeEach, it, module, inject, SourceLoaderServiceTestData, done, expect*/
(function () {
  'use strict';
  describe('myCanvasModule: Services: SourceLoaderService-->\n\t', function () {
    var SourceLoaderService, getTestData;

    getTestData = TestUtils.getTestData.bind(null, SourceLoaderServiceTestData);

    beforeEach(function () {
      module('myCanvasModule');
    });

    beforeEach(function () {
      inject(function ($injector) {
        SourceLoaderService = $injector.get('SourceLoaderService');
      });
    });

    describe('SourceLoaderService.loadImage-->\n\t', function () {
      var testData;
      beforeEach(function () {
        testData = getTestData('loadImage');
      });

      it('should load the source and return the image as response', function (done) {
        var image;
        SourceLoaderService.loadImage(testData.validSource).then(function (response) {
          image = response;
          done();
          console.log('called');
        },function (error) {
          console.log('called', error);
          done();
        });
      });

    });

  });
}());

当我运行测试服时,我得到:

错误:超时 - 未在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内调用异步回调。

我不知道出了什么问题。我是 Karma 和 Jasmine 的新手。感谢您的帮助。

最佳答案

要在 AngularJS 中测试 $q 提供程序的任何用法,您必须创建一个摘要循环以允许在后台解析任何 Promise。您应该尝试以下操作:

it('should load the source and return the image as response', function (done) {
  var image;

  SourceLoaderService.loadImage(testData.validSource)
    .then(function (response) {
      // ... success check
    },function (error) {
      // ... error check
    });

  // Call apply for the above Promise to resolve
  $scope.$apply();
}

编辑:

作为对评论的回应,您还需要按如下方式创建 $scope 变量:

var SourceLoaderService, $scope;

beforeEach(function () {
  inject(function ($injector) {
    SourceLoaderService = $injector.get('SourceLoaderService');
    $scope = $injector.get('$rootScope').$new();
  });
});

关于javascript - Jasmine : Timeout - Async callback was not invoked within timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36882246/

相关文章:

javascript - Angularjs 和 Requirejs : Error: [$injector:modulerr]

javascript - Angular ng-model 不适用于初始值的复选框

javascript - 未调用方法上的 Sinon.spy

javascript - 用于创建模式对话框的 JQuery 编码可以在 jsfiddle 中工作,但不能在本地 html 文件中工作

javascript - Jquery .focusout 不适用于移动设备(slicknav)

javascript - 如何在 firestore 中的集合中的数组上应用过滤器

unit-testing - 没有方法的类应该被测试?

php - 在网页上输入数学字符

javascript - 即使使用 angular.fromJson() 也无法从 json 对象访问字符串

c++ - Visual Studio 2010 的单元测试功能是否可用于 native C++ 代码?