我已经创建了一个服务来模拟我的后端并允许分页内容:
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属性来引发异常。
答案 0 :(得分:0)
好的,根据docs找到解决方案,函数的响应应该是以下stacture的数组[(str)StatusCode,(str,obj)Response,(obj)Headers] < / p>
以下代码有效:
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;
}
}
});