我有一个服务对象调用后端按id获取项目,它工作正常但是当我在测试期间模拟get方法时没有调用方法,我不确定我做错了什么。我正在使用Jasmine2
而不是模拟httpbackend,我使用returnValue
设置响应,但不知何故returnValue没有waorking
这是服务
(function() {
'use strict';
angular
.module('moduleName')
.factory('Project', Project);
Project.$inject = ['$resource'];
function Project ($resource) {
var resourceUrl = 'api/projects/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
}
return data;
}
},
'update': { method:'PUT' }
});
}
})();
控制器看起来像这样
(function () {
'use strict';
angular
.module('moduleName')
.controller('ProjectController', ProjectController);
ProjectController.$inject = ['Project'];
function ProjectControllerr(Project) {
var vm = this;
vm.project = Project.get(1);
}
})();
这是测试
'use strict';
describe('Project Controller Tests', function () {
beforeEach(module('moduleName'));
describe('Project Controller', function () {
var $scope, $state, ProjectMock, stateMock, stateParamsMock;
beforeEach(inject(function ($rootScope) {
$scope = $rootScope.$new();
ProjectMock = jasmine.createSpyObj('Project', ['get']);
ProjectMock.get.and.returnValue({id:1,name:'data'});
stateParamsMock = {projectId: 1};
}));
describe('When a project is not empty', function () {
beforeEach(inject(function ($controller,Project) {
$controller('ProjectsController as vm',
{
$scope: $scope,
Project: ProjectMock,
$state: stateMock
});
}));
it('Should fetch current project by id', function () {
expect(ProjectMock.get).toHaveBeenCalled();
expect($scope.vm.project.id).toBe(1);
});
});
});
});
答案 0 :(得分:0)
您没有致电ProjectMock.get();
这就是您没有得到回复的原因。所以,如果您检查了它,您的期望toHaveBeenCalled
就是假的。
进行以下更改。
it('Should fetch current project by id', function () {
ProjectMock.get();
expect(ProjectMock.get).toHaveBeenCalled();
expect($scope.vm.project.id).toBe(1);
});