AngularM
AngularM

Reputation: 16618

jasmine unit test mock a promise

I'm having trouble testing my promise unit test.

I've put an assertion called "expect(scope.test).toBe(12);". This is inside the promise then where its returned in my code.

Below is my actual code I'm trying to test:

$scope.getBudgets = function(){
    BudgetService.getBudgets().then(function(response) {
        $scope.test = 12;

    }, function(response) {

    });
}

Below is my unit test:

describe('budgetOverviewCtrl tests', function() {

beforeEach(module('app'));
beforeEach(module('ngRoute'));

var ctrl, scope, deferred;

describe('budgetOverviewCtrl with test', function() {
    beforeEach(inject(function($controller, _$rootScope_) {

        scope = _$rootScope_.$new();

        ctrl = $controller('budgetOverviewCtrl', {
            $scope: scope
        });         
    }));

    it('Should check if getBudgets service promise exists and returns as expected', inject(function($injector, $q, BudgetService) { 

        BudgetService = $injector.get("BudgetService");         

        deferred = $q.defer();
        deferred.resolve({"Hello": "World"});   

        spyOn(BudgetService, 'getBudgets').and.callFake(function() {
            return deferred.promise;
        }); 

        scope.getBudgets();

        expect(BudgetService.getBudgets).toHaveBeenCalled();

        **//Below line isnt called - this is inside the promise then.**
        expect(scope.test).toBe(12);
    }));
});
});

Upvotes: 2

Views: 1127

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 26982

It looks like you're missing a call to $rootScope.$apply() after the call to scope.getBudgets() in the test. In Angular, promise success and error callbacks run as part of the digest cycle, which must be manually triggered from tests.

Upvotes: 1

Related Questions