Skip to content

Commit 1abcfe3

Browse files
author
Emmanouil Konstantinidis
committed
Mock superagent
1 parent b3acd4a commit 1abcfe3

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* global jest */
2+
3+
var superagent = jest.genMockFromModule('superagent');
4+
5+
var Response = jest.genMockFunction().mockImplementation(function () {
6+
this.status = 200;
7+
this.ok = true;
8+
});
9+
10+
Response.prototype.send = jest.genMockFunction();
11+
Response.prototype.toError = jest.genMockFunction();
12+
13+
var Request = jest.genMockFunction().mockImplementation(function (method, url) {
14+
this.method = method;
15+
this.url = url;
16+
});
17+
18+
Request.prototype.accept = jest.genMockFunction().mockReturnThis();
19+
Request.prototype.set = jest.genMockFunction().mockReturnThis();
20+
Request.prototype.send = jest.genMockFunction().mockReturnThis();
21+
Request.prototype.field = jest.genMockFunction().mockReturnThis();
22+
Request.prototype.query = jest.genMockFunction().mockReturnThis();
23+
Request.prototype.end = jest.genMockFunction().mockImplementation(function (callback) {
24+
25+
if (superagent.mockDelay) {
26+
this.delayTimer = setTimeout(callback, 0, superagent.mockError, superagent.mockResponse);
27+
28+
return;
29+
}
30+
31+
callback(superagent.mockError, superagent.mockResponse);
32+
});
33+
34+
Request.prototype.abort = jest.genMockFunction().mockImplementation(function () {
35+
this.aborted = true;
36+
37+
if (this.delayTimer) {
38+
clearTimeout(this.delayTimer);
39+
}
40+
});
41+
42+
superagent.Request = Request;
43+
superagent.Response = Response;
44+
45+
superagent.mockResponse = new Response();
46+
superagent.mockError = null;
47+
superagent.mockDelay = false;
48+
49+
function __setResponse (status, ok, body, error) {
50+
var mockedResponse = jest.genMockFunction().mockImplementation(function () {
51+
this.status = status;
52+
this.ok = ok;
53+
this.body = body;
54+
});
55+
56+
superagent.mockError = {
57+
response: {
58+
body: error
59+
}
60+
};
61+
62+
superagent.mockResponse = new mockedResponse();
63+
}
64+
65+
module.exports = {
66+
Response: Response,
67+
Request: Request,
68+
post: function () {
69+
return new Request();
70+
},
71+
get: function () {
72+
return new Request();
73+
},
74+
patch: function () {
75+
return new Request();
76+
},
77+
put: function () {
78+
return new Request();
79+
},
80+
__setResponse: __setResponse
81+
};

0 commit comments

Comments
 (0)