0

I am currently writting tests for one of my AngularJS services in which I have async methods. In my Jasmine test the method is correctly called but I can't retrieve the promise and I get the following error message : Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

I've tested to change the timeout but it doesn't work. After reading other answers I've tested to make a $digest cycle but it doesn't work either.

I've seen solutions in which they mocked the call but I don't want to mock anything because I want to validate that the returned promise is OK.

So my question is, is it possible?

Here you can find my code:

  • the service:

function ping(useXML) {
  var deffered = $q.defer();

  setTimeout(function() {

    deffered.resolve(0);
    console.log("COUCOU");
  }, 500);
  return deffered.promise;
}
  • the test:

"use strict";

describe('Ping test', function() {
    var webservice;

    beforeEach(module('modulename'));
    beforeEach(module('othermodulename'));

    beforeEach(inject(function( _WebService_) {
        webservice = _WebService_;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 3000;
    }));

    it ('ping not null',function(done) {
        var promise = webservice.ping(true);

        promise.then(function (result) {
            expect(result).toEqual(0);
            console.log(result);
            done();

        });
    });
});

Here a what my console shows: enter image description here

We can see that the method is called and that the callback is never invoked.

I don't understand why it is impossible to catch the promise in the test, I've already tried a lot of solutions found on Google and even here on SO. So if you can help me, thank you in advance for your time. And if I forgot anything tell me in order to make me complete.

  • 1
    Sorry if closing the post is a bit harsh but I think the answer is there. In summary, use angular's `$timeout` instead of `setTimeout` and then `$timeout.flush()`in your test – C.Champagne Jun 12 '18 at 10:03
  • Yes thank you that was it. I didn't find this post. Sorry for this. – Mathieu Kostiuk Jun 12 '18 at 10:12
  • Oh that's nothing. It wasn't easy to find but I had the same issue recently so I knew the answer already existed – C.Champagne Jun 12 '18 at 10:23

0 Answers0