Unit-Testing a service in Controller with Jasmine in AngularJS

北城以北 提交于 2019-12-24 11:25:17

问题


In my Controller I've defined the following service:

CrudService.getAllGroups().$promise.then(
    function (response) { $scope.groups = response; },
    function (error) { //error code.. }
);

Well, I want to test this service whether it gets a response or not. In test script at first I've defined a function to check whether the service is defined at all.

Test code:

describe('Ctrl: TestCtrl', function () {
    beforeEach(module('testApp'));

    var scope,
        CrudService,
        ctrl,
        backend;

    beforeEach(inject(function ($controller, $rootScope, _CrudService_, $httpBackend) {
        scope = $rootScope.$new();

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

        CrudService = _CrudService_;

        backend = $httpBackend;     
    }));

    it('should defined the service getGroups', function () {
        expect(CrudService.getGroups).toBeDefined();
    });

    //this is wrong!
    it('should returns a successful response', function () {
        backend.expectGET('http://localhost:63831/api/group').respond(200, 'success');
        backend.flush();
    });
});

I don't know how to get a response in the test. I'm new in unit testing and need some help.

For a better comprehension here is the service code:

//CrudService file:
...
return {
         getAllGroups: function () {
             return ResService.group.query();
         }
}
...


//ResService file:
return {
         group: $resource(baseUrl + '/api/group/:Id', {
           Id: '@Id'
         }, {})
}

Do anyone has an idea?


回答1:


It's incorrect in the sense that it's not a unit test. If you are testing controller here, then you should mock CrudService and test that $scope.groups has been assigned correctly.

beforeEach(function () {
    module(function ($provide) {
        $provide.factory('CrudService', function () {
            return {
                getAllGroups: function () {
                    return {
                        $promise: null // return an actual promise here
                    }
                }
            }
        });
    });
});
it('should set groups', function () {
    expect($scope.groups).toEqual('success')
});

And you need a separate spec to test if CrudService calling backend correctly.



来源:https://stackoverflow.com/questions/32694087/unit-testing-a-service-in-controller-with-jasmine-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!