Skip to content

Commit f7bab19

Browse files
committed
The result could be status and data
1 parent 34bd68d commit f7bab19

File tree

2 files changed

+38
-6
lines changed

2 files changed

+38
-6
lines changed

src/index.js

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { parseRequest, matchUrl } from './util';
2+
import Response from './response';
23

34
class FetchMock {
45
constructor(required) {
@@ -26,8 +27,12 @@ class FetchMock {
2627
loadMock(key, mock) {
2728
if ('object' !== typeof mock) {
2829
if ('function' === typeof mock) {
30+
var items = key.split(' ');
31+
var method = items.length === 2 ? items[0] : 'GET';
32+
var url = items.length === 2 ? items[1] : key;
2933
this.urls.push({
30-
url: key,
34+
method,
35+
url,
3136
func: mock,
3237
});
3338
}
@@ -43,7 +48,7 @@ class FetchMock {
4348
let insideParams;
4449
const filters = this.urls.filter(uri => {
4550
const obj = matchUrl(uri.url, request.url);
46-
if (obj.result) {
51+
if (obj.result && uri.method.toUpperCase() === request.method.toUpperCase()) {
4752
insideParams = obj.params;
4853
return true;
4954
}
@@ -62,11 +67,13 @@ class FetchMock {
6267
if ('function' !== typeof mock.func) {
6368
throw new Error('There is no url defined in __mocks__');
6469
}
65-
const promise = mock.func(request);
66-
if (!promise || 'function' !== typeof promise.then) {
67-
throw new Error('The result of mock function should be a promise.');
70+
const obj = mock.func(request);
71+
if (!obj || 'object' !== typeof obj) {
72+
throw new Error('The result of mock function should be an object.');
6873
}
69-
return promise;
74+
75+
const response = new Response(obj);
76+
return Promise.resolve(response);
7077
}
7178
}
7279

src/response.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
class Response {
3+
constructor({
4+
status,
5+
data = {},
6+
}) {
7+
this.status = status;
8+
this.data = data;
9+
}
10+
11+
text() {
12+
try {
13+
return Promise.solve(JSON.stringify(data));
14+
} catch (err) {
15+
return Promise.reject(new Errror('failed text invoke.'));
16+
}
17+
}
18+
19+
json() {
20+
return this.data;
21+
}
22+
23+
}
24+
25+
export default Response;

0 commit comments

Comments
 (0)