Skip to content

Commit 06724be

Browse files
committed
add test to cover GET method handling and fix GET handling
This is derived from PR #55
1 parent d4f7dd3 commit 06724be

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

graphql.js

+15-7
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@
3131
})
3232
}
3333

34+
function __handleMethod(method, url, data, asJson) {
35+
var cleaned = {url: url};
36+
var isGet = method.toUpperCase() === 'GET';
37+
if (asJson && !isGet) {
38+
cleaned.body = JSON.stringify({query: data.query, variables: data.variables});
39+
} else {
40+
cleaned.url = url + '?' + "query=" + encodeURIComponent(data.query) + "&variables=" + encodeURIComponent(JSON.stringify(data.variables))
41+
}
42+
return cleaned;
43+
}
44+
3445
var __doRequest
3546

3647
if (typeof XMLHttpRequest !== 'undefined') {
@@ -87,11 +98,8 @@
8798
if (!url) {
8899
return;
89100
}
90-
if (asJson) {
91-
var body = JSON.stringify({query: data.query, variables: data.variables});
92-
} else {
93-
var body = "query=" + encodeURIComponent(data.query) + "&variables=" + encodeURIComponent(JSON.stringify(data.variables))
94-
}
101+
var cleaned = __handleMethod(method, url, data, asJson);
102+
95103
if (debug) {
96104
console.groupCollapsed('[graphql]: '
97105
+ method.toUpperCase() + ' ' + url + ': '
@@ -110,11 +118,11 @@
110118

111119
__doRequest(
112120
method,
113-
url,
121+
cleaned.url,
114122
asJson ? 'application/json' : 'application/x-www-form-urlencoded',
115123
'application/json',
116124
headers,
117-
body,
125+
cleaned.body,
118126
onRequestError,
119127
callback
120128
)

test/test.js

+13
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,19 @@ fragment auth_error on Error {messages}`;
200200

201201
set('url', () => 'https://example.org');
202202

203+
describe('when method is GET', () => {
204+
set('method', () => 'get');
205+
206+
it('makes the request passing the parameters as query arguments', () => {
207+
let xhr = mockXHR(200, {});
208+
xhr.send = jest.fn();
209+
fetchPost({id: 123});
210+
expect(xhr.send).toHaveBeenCalledWith(undefined);
211+
expect(xhr.open).toHaveBeenCalledWith(method, expect.stringMatching(url), true)
212+
expect(xhr.open).toHaveBeenCalledWith(method, expect.stringMatching(/\?query=.+&variables=/), true)
213+
});
214+
});
215+
203216
describe('when executing the queries normally', () => {
204217
it('sends a network request right away', () => {
205218
let xhr = mockXHR(200, {});

0 commit comments

Comments
 (0)