我正在尝试用茉莉花间谍编写单元测试用例。以下是我的服务代码。
function reset(someParam) {
var deferred = $q.defer();
svcTypes.getTasksWithRoles().then(function (types) {
if (types.HadError) return;
// do some stuff..
deferred.resolve(results);
}, function (errorResponse) {
deferred.reject(errorResponse);
});
return deferred.promise; }
以下是我的单元测试用例:
describe('tests for svcWorkordertypes', function () {
beforeEach(angular.mock.module('workorders.service'));
beforeEach(angular.mock.module('workordertypes.service'));
var svcWorkordertypes;
var svcTypes;
var $q, $httpBackend;
beforeEach(angular.mock.inject(function (_svcWorkordertypes_, _svcTypes_, _$q_, _$httpBackend_) {
svcWorkordertypes = _svcWorkordertypes_;
svcTypes = _svcTypes_;
$q = _$q_;
$httpBackend = _$httpBackend_;
}));
//This is working fine.
it('all controls should be set', function () {
expect(svcWorkordertypes).toBeDefined();
expect(svcTypes).toBeDefined();
expect($q).toBeDefined();
expect($httpBackend).toBeDefined();
});
it('test reset method', function () {
//Arrange
var someParam = 'test';
var types = [{ RoleList: 'newRoleList', isHeader: true, Roles: 'testRole' }];
$httpBackend.when("GET", 'null/tasks/types?$select=IncludeRoles').respond(200, JSON.stringify(types));
spyOn(svcTypes, 'getTasksWithRoles').and.returnValue(function () {
var deferred = $q.defer();
deferred.resolve(JSON.stringify(types));
return deferred.promise;
});
//Act
var result = svcWorkordertypes.reset(selectedRoleName);
//Assert
result.then(function (res) {
console.log(res + ' res output...');
//expect(JSON.stringify(res)).toEqual(JSON.stringify(types));
});
//expect(svcTypes).toBeDefined();
}) });
以下是错误:
我也尝试过callFake的很多方法。我在stackoverflow上发现了一个类似的问题,但它对我没有帮助。
答案 0 :(得分:2)
getTasksWithRoles
应该返回一个promise,并且它被模拟返回一个返回promise的函数。
应该是:
spyOn(svcTypes, 'getTasksWithRoles').and.returnValue(
$q.resolve(JSON.stringify(types))
);