3

I was following this example.

We have test suite like:

describe('Basic Test Suite', function(){
    var DataService, httpBackend;

    beforeEach(module('iorder'));
    beforeEach(inject(
        function (_DataService_, $httpBackend) {
            DataService = _DataService_;
            httpBackend = $httpBackend;
        }
    ));
    //And following test method:
    it('should call data url ', function () {
        var promise = DataService.getMyData();
        promise.then(function(result) { 
            console.log(result, promise); // Don't gets here
        }).finally(function (res) {  
            console.log(res); // And this is also missed
        })
    })
});

How to make jasmine + karma work with angular services, that returns promise?

I have seen this question, but looks like it's about using promises in test cases. Not about testing promises.

Community
  • 1
  • 1
Nikolay Fominyh
  • 8,946
  • 8
  • 66
  • 102

1 Answers1

2

You need to tell jasmine that your test is asynchronous so that it waits for the promises to resolve. You do this by adding a done parameter to your test:

describe('Basic Test Suite', function(){
    var DataService, httpBackend;

    beforeEach(module('iorder'));
    beforeEach(inject(
        function (_DataService_, $httpBackend) {
            DataService = _DataService_;
            httpBackend = $httpBackend;
        }
    ));
    //And following test method:
    it('should call data url ', function (done) {
        var promise = DataService.getMyData();
        promise.then(function(result) { 
            console.log(result, promise); // Don't gets here
            done();//this is me telling jasmine that the test is ended
        }).finally(function (res) {  
            console.log(res); // And this is also missed
            //since done is only called in the `then` portion, the test will timeout if there was an error that by-passes the `then`
        });
    })
});

By adding done to the test method, you are letting jasmine know that it is an asynchronous test and it will wait until either done is called, or a timeout. I usually just put a call to done in my then and rely on a timeout to fail the test. Alternatively, I believe you can call done with some kind of error object which will also fail the test, so you could call it in the catch.

pgreen2
  • 3,601
  • 3
  • 32
  • 59