-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathFetchSpec.js
97 lines (79 loc) · 2.59 KB
/
FetchSpec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
describe("$.fetch", function() {
var server,
data = "foo=b%20ar&baz=yolo",
headers = {foo: "bar", "Content-type": "yadda;charset=utf-8"};
before(function() {
server = sinon.fakeServer.create();
server.respondWith("POST", "/json", function (request) {
request.respond(200, request.requestHeaders, request.requestBody);
});
server.respondWith("GET", /\/json\??(.*)/, function (request, query) {
request.respond(200, request.requestHeaders, query);
});
});
after(function () {
server.restore();
});
it("exists", function () {
expect($.fetch).to.exist;
expect(Bliss.fetch).to.exist;
});
describe("POST", function () {
it("POSTs data (URLencoded string)", function () {
return verifyResponseBody("POST", data, "foo=b ar&baz=yolo");
});
it("handles method type in any case", function () {
return verifyResponseBody("post", data, "foo=b ar&baz=yolo");
});
it("sets provided headers", function () {
return verifyResponseHeaders("POST", headers, headers);
});
it("sets Content-type header for POST if not provided", function () {
return verifyResponseHeaders("POST", {}, {
"Content-type": "application/x-www-form-urlencoded;charset=utf-8"
});
});
it("catch 404", function (done) {
handleJSON("/bad", "POST", "").catch(function () {
done();
});
});
});
describe("GET", function () {
it("GETs data (URLencoded string)", function () {
return verifyResponseBody("GET", data, "foo=b ar&baz=yolo");
});
it("handles method type in any case", function () {
return verifyResponseBody("get", data, "foo=b ar&baz=yolo");
});
it("sets provided headers", function () {
return verifyResponseHeaders("GET", headers, headers);
});
it("catch 404", function (done) {
handleJSON("/bad", "GET", "").catch(function () {
done();
});
});
});
function handleJSON(url, method, data, headers) {
var then = $.fetch(url, {
method: method,
data: data,
headers: headers || {}
});
server.respond();
return then;
}
function verifyResponseBody(method, data, expected) {
var promise = handleJSON("/json", method, data);
return promise.then(function (response) {
expect(response.response).to.equal(encodeURI(expected));
});
}
function verifyResponseHeaders(method, headers, expected) {
var promise = handleJSON("/json", method, "", headers);
return promise.then(function (response) {
expect(response.responseHeaders).to.deep.equal(expected);
});
}
});