Mike Wang
Mike Wang

Reputation: 87

How to test angular promise with Jasmine

The test below. When I try to test it with Jasmine, the console.log in then is never called. what is the issue with the code, is it related with angular or jasmine?

describe("angular test", function() {

  var $q;

  beforeEach(function() {
    angular.mock.inject(function getDependencies(_$q_) {
      $q = _$q_;
    });
  });

  it("angular nested promise with jasmine", function(done) {

    $q(function(resolve, reject) {
        resolve(10);
      })
      .then(function(r) {
        console.log(r);
      })
      .finally(function() {
        done();
      });
  });
})
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.5/angular-mocks.js"></script>

Thanks Merott, that solve the problem.

Second question:

if I am testing a service that return a promise. The promise is wrapped in the service. I also need to add that digest to make it work. Is the digest needed only for jasmine or even in normal case?(I mean for the service.)

Upvotes: 2

Views: 153

Answers (1)

Merott
Merott

Reputation: 7369

You must trigger the digest by injecting $rootScope and calling $rootScope.$digest().

describe("angular test", function() {

  var $q, $rootScope;

  beforeEach(function() {
    angular.mock.inject(function getDependencies(_$q_, _$rootScope_) {
      $q = _$q_;
      $rootScope = _$rootScope_;
    });
  });

  it("angular nested promise with jasmine", function(done) {
    $q(function(resolve, reject) {
      console.log('hello');
      resolve(10);

    }).then(function(r) {
      console.log(r);
    }).finally(function() {
      done();
    });
    
    $rootScope.$digest();
  });
})
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.5/angular-mocks.js"></script>

Upvotes: 4

Related Questions