在没有setTimeout的情况下测试异步函数

时间:2018-04-02 19:27:56

标签: javascript angularjs jasmine angular-promise

如果有人可以帮我测试这个功能而不使用我在测试文件中使用的setTimeout,我希望如此。经过大量的研究后,我能够实现它,但是setTimeout是一颗定时炸弹。 我用茉莉花的承诺和千种不同的方式进行了探究,但没有一种方法有效。

服务:

angular.module('moduloPrueba', [])
  .factory('asincronico', function($q) {

  return {
    tes:tes,
  };


  function tes(){
    var deferred = $q.defer();

    setTimeout(function () {

      deferred.resolve(79);
    }, 50);

    // Return the deferred promise
    return deferred.promise;
  }

});  

茉莉花测试:

describe('description', function () {
  var asi;
  var root;
  var res;

  beforeEach(function () {
    module('moduloPrueba');
    inject(function (asincronico, $rootScope) {
      root = $rootScope;
      asi = asincronico;
    })
  });

  it('should ', function (done) {
    asi.tes().then(function (resp) {
      res = resp;
      done();
    });

    setTimeout(function () {
      root.$digest();
      expect(res).toEqual(79);
      expect(res).not.toEqual(123);
    }, 200);

  });

});

1 个答案:

答案 0 :(得分:0)

使用$timeout服务代替setTimeout

angular.module('moduloPrueba', [])
    .factory('asincronico', function ($q, $timeout) {

        return {
            tes: tes
        };


        function tes() {
            var deferred = $q.defer();

            $timeout(function () {

                deferred.resolve(79);
            }, 50);

            // Return the deferred promise
            return deferred.promise;
        }

    });

然后在测试中调用$timeout.flush()以等待超时完成,然后$rootScope.$digest()以获得解决的承诺。您也不再需要done回调,因为它将同步运行。

describe('description', function () {
    var asi;
    var root;
    var timeout;

    beforeEach(function () {
        module('moduloPrueba');
        inject(function (asincronico, $rootScope, $timeout) {
            root = $rootScope;
            asi = asincronico;
            timeout = $timeout;
        })
    });

    it('should ', function () {

        asi.tes().then(function (resp) {
            expect(resp).toEqual(79);
            expect(resp).not.toEqual(123);
        });

        timeout.flush();
        root.$digest();
    });

});