Page 268 - AngularJS权威教程
P. 268
248 第 19 章 测试
data(可选):HTTP请求的主体,或者是个函数,接受一个data字符串并且在data符合
预期时返回true(或者是一个用JSON格式发送HTTP主体的JavaScript对象);
headers(可选):HTTP头或者函数,该函数接收header对象作为参数,并且在headers
匹配预期时返回true。
except方法返回一个对象,该对象的respond方法用于控制在测试中如何处理匹配请求。
describe('Remote tests', function() {
var $httpBackend, $rootScope, myService;
beforeEach(inject(
function(
_$httpBackend_, _$rootScope_, _myService_) {
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
// myService是一个服务
// 为我们产生HTTP调用
myService = _myService_;
}));
it('should make a request to the backend', function() {
// 建立一个预期
// myService会向路由发送一个GET请求
// /v1/api/current_user
$httpBackend.expect('GET', '/v1/api/current_user')
.respond(200, {userId: 123});
myService.getCurrentUser();
// 冲刷请求很重要
$httpBackend.flush();
});
});
$httpBackend.expect方法带有几个帮助函数,让我们能更加具体地描述设置的预期。
expectGET()为GET方法创建了一个新的请求预期,expectGET()带有两个参数。
url:一个HTTP URL或者接受URL的函数,并且该URL匹配当前定义时返回true。
headers(可选):HTTP头。
// ...
$httpBackend.expectGET("/v1/api/current_user")
expectHEAD()为HEAD方法创建了一个新的请求预期。它带有两个参数。
url:一个HTTP URL或者接受URL的函数,并且该URL匹配当前定义时返回true。
headers(可选):HTTP头。
// ...
$httpBackend.expectHEAD("/v1/api/current_user")
expectJSONP()为JSONP请求创建了一个新的请求预期。它只带有一个参数。
url:一个HTTP URL或者接受URL的函数,并且该URL匹配当前定义时返回true。
// ...
$httpBackend.expectJSONP("/v1/api/current_user")
expectPATCH()为PATCH请求创建了一个新的请求预期。它接受三个参数。