在AngularJS单元测试服务在控制器茉莉花 [英] Unit-Testing a service in Controller with Jasmine in AngularJS

查看:123
本文介绍了在AngularJS单元测试服务在控制器茉莉花的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器我已经定义了以下服务:

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.

测试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.

为了更好地融为一体$ P $这里phension是服务code:

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?

推荐答案

这是在这个意义上不正确,它不是一个单元测试。如果你在这里测试控制器,那么你应该嘲笑 CrudService 并测试 $ scope.groups 已正确分配。

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')
});

而你需要一个单独的规范来测试是否 CrudService 调用正确的后端。

这篇关于在AngularJS单元测试服务在控制器茉莉花的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆