0

我在尝试测试方法控制器时遇到了一些问题。所以,这是我的控制器,名为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);
        });
    });
})

我想测试当我运行 save 方法时是否真的有效。

4

1 回答 1

0

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

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

如果要检查控制器方法是否调用了工厂方法,则需要创建一个 spy,然后在调用控制器函数后检查是否调用了 spy:

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()
        });
    });
});
于 2015-08-04T09:07:54.203 回答