在jasmine中访问函数内的scope.variables

时间:2015-06-12 06:26:09

标签: angularjs unit-testing jasmine karma-runner karma-jasmine

我试图让断言$scope.buttonDisable变量位于save()内。这是测试用例

describe('EditMeetingCtrl.save()', function () {
        var $rootScope, scope, $controller , $q  , state ,  controller ;

        var companyService , meetingService  ;

        beforeEach(angular.mock.module('MyApp'));

        beforeEach(angular.mock.inject(function (_$httpBackend_, _companyService_ , _meetingService_ ) {
            $httpBackend = _$httpBackend_;
            companyService = _companyService_;
            meetingService = _meetingService_ ;
        }));

        beforeEach(inject(function ($rootScope, $controller , $state , _meetingService_ ) {
            scope = $rootScope.$new();
            createController = function() {
                return $controller('EditMeetingCtrl', {
                $scope: scope,
                meeting : {} ,
                meetingService : _meetingService_
                }); 
            };
             controller = new createController();
        }));

        it("buttonDisable should equal to false", function() {
            expect(controller.save.buttonDisable).toEqual(false);
        });

    });

这是我的控制器。

(function() {
    'use strict';

    angular
        .module('MyApp')
        .controller('EditMeetingCtrl', EditMeetingCtrl);

    EditMeetingCtrl.$inject = ['$rootScope', '$scope', '$state', '$http'];

    function EditMeetingCtrl($rootScope, $scope, $state, $http) {

        $scope.save = save;


        function save() {
            meetingService.saveMeeting()
                .success(function(meetingId) {
                    $scope.mainMeetingForm.$setPristine();
                    $scope.buttonDisable = false;

                });
        }

    }
})();

我想测试一下,当调用save()时,scope.buttonDisable将等于false。从我上面的测试我得到的是以下

PhantomJS 1.9.8 (Windows 8) In EditMeetingCtrl EditMeetingCtrl.save() should save the meeting FAILED
        TypeError: 'undefined' is not an object (evaluating 'controller.save.buttonDisable')

有人可以告诉我如何在scope.variable内访问此save()吗?

1 个答案:

答案 0 :(得分:1)

看看是否有效,

    it("buttonDisable should equal to false", function() {
        scope.save();
        /* However here you have to flush any http request or $timeout using 
           $httpBackend.flush() and $timeout.flush() respectively 
           for success function to get called.
        */
        expect(scope.buttonDisable).toEqual(false); //assertion
    });