AngularJs单元测试 - 在promise解决后调用的函数

时间:2015-02-08 17:33:25

标签: angularjs unit-testing jasmine

我想测试我的服务电话是否成功以及该功能"搜索"在服务电话后被呼叫。

我的控制器:

function UnitTestsCtrl(homePSrv, $scope) {
    var that = this;
    this.SearchModel = {};
    this.homePSrv = homePSrv;
}

UnitTestsCtrl.prototype.Init = function() {
     var that = this;
    this.homePSrv.InitUnitTestSearchModel().then(function(result) {
        that.SearchModel = result;
        that.Search();
    });
}

angular.module("unitTestsCtrl", [])
       .controller("unitTestsCtrl", UnitTestsCtrl);

茉莉花单元测试:

describe('Controller Tests: "UnitTestsCtrl"', function () {
    var ctrl, mockHomePSrv;

    beforeEach(function () {
        mockHomePSrv = jasmine.createSpyObj('homePSrv', ['InitUnitTestSearchModel']);
        module('app.main');

        inject(function ($controller, $q) {

            mockHomePSrv.InitUnitTestSearchModel.and.returnValue($q.when('InitUnitTestSearchModelData'));

            ctrl = $controller('unitTestsCtrl', {
                homePSrv: mockHomePSrv,
            });
        });
    });

  it('Funktion "Search" was called', function () {
        spyOn(ctrl, 'Init');
        spyOn(ctrl, 'Search');
        ctrl.Init();
        expect(ctrl.Init).toHaveBeenCalled();

        //Thats not working - its not being called
        expect(ctrl.Search).toHaveBeenCalled();

    });
});

问题是如果调用搜索函数的期望是假的。我认为这与承诺有关。

解决方案:

 spyOn(ctrl, 'Search');
 ctrl.Init();
 $scope.$digest()   //I've inserted this and everything works fine now
 expect(ctrl.Init).toHaveBeenCalled();
 expect(ctrl.Search).toHaveBeenCalled();

0 个答案:

没有答案