1

我是 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;
});
4

1 回答 1

0

当你想执行挂起的请求时,你需要调用 $httpBackend.flush() :

$httpBackend.expectGET('/daf/rest/user/').respond(userData);
user = UserService.getUser(username);
$httpBackend.flush();
dump(user);
expect(user).toEqualData(userData);

更新(基于您向我们展示的新代码):您正在执行 ajax 请求并且它们是异步的。您调用 $http.get 函数,您只会看到服务器处理您的请求时的实际结果。当 UserService 方法返回用户时,服务器(在本例中为 httpBackend 模拟)尚未处理请求。但是 $http 有一个很棒的功能:它允许你返回 Promise。该对象由 $http 方法立即返回,并且当服务器(或您的模拟)处理请求时,承诺得到履行。您可以在此处查看示例: 处理服务中的 $http 响应

我建议您阅读有关promises的内容。

于 2013-07-24T16:16:17.363 回答