使用 jasmine 测试控制器是否在 angularjs 中工作

Testing if a controller works in angularjs using jasmine

我在尝试测试方法控制器时遇到了一些问题。 所以,这是我的控制器,名为 contactCtrl

'use strict';

(function () {
    angular.module('routerApp').controller('ContactController', function ($scope, contactRepository) {

        $scope.saveContact = function(selectedContact) {
            $scope.errors = [];

            contactRepository.saveContactInfo(selectedContact);

            $scope.contactSelected = false;
        };

        $scope.cancel = function() {
            $scope.contactSelected = false;
            $scope.selectedContact = null;
        };

        $scope.selectContact = function(contact) {
            $scope.contactSelected = true;
            $scope.selectedContact = contact;
        };
    });
}());

这是我的联系人资料库

'use strict';

(function () {
    angular.module('routerApp').factory('contactRepository', function() {
        return {
            saveContactInfo: function (selectedContact) {
                console.log(selectedContact);
            }
        };
    });
}());

这是我的规范文件,名为 contactCtrl.spec.js

describe('Controller',function() {

    var scope,contactCtrl;

    beforeEach(module('routerApp'));
    beforeEach(inject(function ($rootScope, $controller) {
       scope = $rootScope.$new();
       contactCtrl = $controller('ContactController',{$scope:scope});
    }));

    describe('ContactController', function() {
        it('save method should have contactSelected false', function() {
            expect(contactCtrl.contactSelected).toBe(false);
        });
    });
})

我想测试 运行 保存方法是否有效。

您必须实际调用该函数,然后断言该值是您所期望的。所有这些都需要在您的 scope 变量而不是控制器上完成。

describe('ContactController', function() {
    it('save method should have contactSelected false', function() {
        expect(scope.contatSelected).toBeUndefined();
        scope.saveContact('foo');
        expect(scope.contactSelected).toBe(false);
    });
});

如果您想检查您的控制器方法是否调用了您的工厂方法,您将需要创建一个间谍,然后在调用控制器函数后检查是否已调用间谍:

describe('Controller',function() {

    var scope,contactCtrl, contactRepository;

    beforeEach(module('routerApp'));
    beforeEach(inject(function ($rootScope, $controller, _contactRepository_) {
       scope = $rootScope.$new();

       // inject your factory so we can spy on it
       contactRepository = _contactRepository_;
       contactCtrl = $controller('ContactController',{$scope:scope});

       // create spy
       spyOn(contactRepository, 'saveContactInfo');
    }));

    describe('ContactController', function() {
        it('save method should have contactSelected false', function() {
            expect(scope.contatSelected).toBeUndefined();
            scope.saveContact('foo');
            expect(scope.contactSelected).toBe(false);

            // assert that function was called
            expect(contactRepository.saveContactInfo).toHaveBeenCalled()
        });
    });
});