1 | 'use strict';
|
2 |
|
3 | module.exports = (Grown, util) => {
|
4 | const MockReq = require('mock-req');
|
5 |
|
6 | function _mockRequest(options) {
|
7 | const _body = options.body;
|
8 |
|
9 | const req = new MockReq(options);
|
10 |
|
11 |
|
12 | if (typeof _body === 'object') {
|
13 | req.body = _body;
|
14 | return req;
|
15 | }
|
16 |
|
17 | delete options.body;
|
18 |
|
19 | try {
|
20 | if (_body) {
|
21 | if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'DELETE') {
|
22 | throw new Error(`${req.method} requests does not need body, given ${JSON.stringify(_body)}`);
|
23 | }
|
24 |
|
25 | if (Buffer.isBuffer(_body) || typeof _body === 'string') {
|
26 | req.write(_body);
|
27 | }
|
28 |
|
29 | if (typeof _body.pipe === 'function') {
|
30 | _body.pipe(req);
|
31 | }
|
32 | }
|
33 | } catch (e) {
|
34 | e.summary = `Invalid request, given '${util.inspect(options)}'`;
|
35 |
|
36 | throw e;
|
37 | }
|
38 |
|
39 | return req;
|
40 | }
|
41 |
|
42 | return Grown('Test.Mock.Req', {
|
43 |
|
44 | _mockRequest,
|
45 |
|
46 | $mixins(options) {
|
47 | const req = this._mockRequest(options);
|
48 |
|
49 | return {
|
50 | props: {
|
51 | req: () => req,
|
52 | },
|
53 | };
|
54 | },
|
55 | });
|
56 | };
|