1

我创建了一个服务来模拟我的后端并允许分页内容:

angular.module('testedApp')
    .service('mockedResponses', function mockedResponses() {

   var _mediaResponse = {"total":84,"media":[...], groups: {}, keywords: {}};


    return {
        getMediaResponse: function(method, url, data, headers){
            var mediaResponse = angular.copy(_mediaResponse),
                start = headers.skip_current || 0,
                end = headers.limit || 8;

            mediaResponse['media'] = _mediaResponse['media'].splice(start, end);
            return mediaResponse;
        }
    }
});

测试:

'use strict';

describe('Controller: CuratorCtrl', function () {

    // load the controller's module
    beforeEach(module('curationApp'));

    var MainCtrl,
        scope,
        mockedResponses,
        $httpBackend;

    // Initialize the controller and a mock scope
    //Use double underline suffix and prefix to prevent shadowing the outer scope dependencies
    //with the inner scope ones
    beforeEach(inject(function ($controller, $rootScope, _$api_, _Message_,
                                    _tileService_, _$state_, _$httpBackend_, _mockedResponses_) {
        //mock the backend
        $httpBackend = _$httpBackend_
        mockedResponses = _mockedResponses_;
        $httpBackend.whenGET(/customer/).respond(mockedResponses.getCustomerResponse);
        $httpBackend.whenGET(/curation\/media/).respond(mockedResponses.getMediaResponse);

        scope = $rootScope.$new();
        MainCtrl = $controller('CuratorCtrl', {
            $scope: scope,
            $api: _$api_,
            Message: _Message_,
            tileService: _tileService_,
            $state: _$state_,
            $stateParams: {}
        });
    }));


    it('should fetch initial batch of media, and place it on the scope', function(){
        $httpBackend.expectGET('/customer');
        $httpBackend.expectGET('/curation/media');
        scope.$digest();
        $httpBackend.flush();
        expect(scope.groups).toBe(mockedResponses.getMediaResponse().groups);
        expect(scope.hashtags).toBe(mockedResponses.getMediaResponse().keywords);
        expect(scope.media).toBe(mockedResponses.getCustomerResponse());
    });

});

而不是预期的数据(媒体),我在范围内得到“null”,并且通过尝试访问 null 的属性引发异常。

4

1 回答 1

0

好的,找到了解决方案,根据文档,函数的响应应该是以下结构的数组 [(str)StatusCode, (str, obj)Response, (obj)Headers]

以下代码有效:

angular.module('testedApp')
    .service('mockedResponses', function mockedResponses() {

   var _mediaResponse = {"total":84,"media":[...], groups: {}, keywords: {}};


    return {
        getMediaResponse: function(method, url, data, headers){
            var mediaResponse = angular.copy(_mediaResponse),
                start = headers.skip_current || 0,
                end = headers.limit || 8;

            mediaResponse['media'] = _mediaResponse['media'].splice(start, end);
            return arguments.length ? ['200', mediaResponse, {}] : mediaResponse;
        }
    }
});
于 2014-10-12T11:20:00.357 回答