我是Angular和Jasmine的新手,我正在尝试使用Angular和Jasmine进行测试,并且无法获得$ httpBackend.expectGet来返回我的JSON对象。我在下面有一个基本测试。有人可以告诉我我做错了吗?这是我的代码:
'use strict';
/* jasmine specs for services go here */
var userData = {
id:1,
firstName:"John",
lastName:"Doe",
username:"jdoe",
email:"John.Doe@blah.com",
phone:"5555551456",
password:"changeme"
}
/*beforeEach(inject(function(_UserService_, $injector) {
UserService = _UserService_;
$httpBackend = $injector.get('$httpBackend');
$httpBackend.expect('GET', '/daf/rest/user/').respond(userData);
}));*/
//TODO: isn't properly stubbing the http return data
describe('Service: UserService', function() {
var UserService, $httpBackend;
beforeEach(function() {
module('cdicms.services.user');
inject(function(_$httpBackend_, _UserService_) {
$httpBackend = _$httpBackend_;
UserService = _UserService_;
});
});
it('should not be undefined', function() {
expect(UserService).toBeDefined();
});
it('should not be undefined', function() {
expect($httpBackend).toBeDefined();
});
it('should get user json based on username', function() {
var user;
var username = "jdoe";
$httpBackend.expectGET('/daf/rest/user/').respond(userData);
//dump(username);
user = UserService.getUser(username);
//dump(user);
//expect(user).toEqualData(userData);
});
});
以下是服务代码:
var userServices = angular.module('cdicms.services.user', []);
userServices.factory('UserService', function($http) {
var service = {};
var User = function() {
this.firstName = '';
this.lastName = '';
this.userName = '';
this.emailAddress = '';
this.phoneNumber = '';
this.password = '';
};
service.getUser = function(username) {
var user;
$http({method: 'GET', url: '/daf/rest/user/'}).
success(function(data, status, headers, config) {
user = new User();
user.id = data.id;
user.firstName = data.firstName;
user.lastName = data.lastName;
user.userName = data.username;
user.emailAddress = data.email;
user.phoneNumber = data.phone;
user.password = data.password;
}).
error(function(data, status, headers, config) {
console.log(data);
dump(data);
});
return user;
};
return service;
});
答案 0 :(得分:0)
如果要执行待处理的请求,则需要调用$ httpBackend.flush():
$httpBackend.expectGET('/daf/rest/user/').respond(userData);
user = UserService.getUser(username);
$httpBackend.flush();
dump(user);
expect(user).toEqualData(userData);
UPDATE(基于您向我们展示的新代码):您正在执行ajax请求并且它们是异步的。您调用$ http.get函数,只需在服务器处理您的请求时看到实际结果。当UserService方法返回用户时,服务器(在本例中为httpBackend mock)尚未处理请求。但$ http有一个很好的设施:它允许你返回承诺。 $ http方法通过immediatily返回此对象,当服务器(或您的模拟)处理请求时,承诺得以实现。你可以在这里看到一个例子: Processing $http response in service
我建议您阅读promises。