Test an asynchronous function with jasmine without using setTimeout

0

I would like if someone can help me to test this function without using the setTimeout I am using in the TEST FILE. after investigating a lot I could make it walk, but that setTimeout is a time bomb. probe with jasmine-promises and in a thousand different ways but none of them worked for me

service:

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;
  }

});  

jasmine test:

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);

  });

});
    
asked by Ivan Paredes 02.04.2018 в 23:13
source

1 answer

0

According to the documentation for it ()

If you want to try a function like this:

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

    setTimeout(function () {

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

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

Then you should write the test as:

it('should resolve 79 after 50ms', function (done) {
    asi.tes().then(function (resp) {
      expect(resp).toEqual(79);
      done();
    });
}, 51);

The result of the promise resp you try in the success callback and the time that should delay the promise, you specify it as the last argument in it

    
answered by 04.04.2018 в 07:10