How to use responseMustHaveEmptyBody method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

http-utils.js

Source: http-utils.js Github

copy
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3    return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.lenientOptions = exports.responseMustHaveEmptyBody = void 0;
7const lodash_1 = __importDefault(require("lodash"));
8// https://github.com/cypress-io/cypress/issues/4298
9// https://tools.ietf.org/html/rfc7230#section-3.3.3
10// HEAD, 1xx, 204, and 304 responses should never contain anything after headers
11const NO_BODY_STATUS_CODES = [204, 304];
12function responseMustHaveEmptyBody(req, res) {
13    return lodash_1.default.includes(NO_BODY_STATUS_CODES, res.statusCode) || (req.method && req.method.toLowerCase() === 'head');
14}
15exports.responseMustHaveEmptyBody = responseMustHaveEmptyBody;
16/**
17 * HTTP options to make Node.js's HTTP libraries behave as leniently as possible.
18 *
19 * These should be used whenever Cypress is processing "real-world" HTTP requests - like when setting up a proxy
20 * server or sending outgoing requests.
21 */
22exports.lenientOptions = {
23    // increase header buffer for incoming response (ClientRequest) request (Server) headers, from 16KB to 1MB
24    // @see https://github.com/cypress-io/cypress/issues/76
25    maxHeaderSize: Math.pow(1024, 2),
26    // allow requests which contain invalid/malformed headers
27    // https://github.com/cypress-io/cypress/issues/5602
28    insecureHTTPParser: true,
29};
30
Full Screen

proxy.js

Source: proxy.js Github

copy
1(function() {
2  var NO_BODY_STATUS_CODES, Promise, REDIRECT_STATUS_CODES, _, accept, blacklist, buffers, charset, concat, conditional, cors, cwd, debug, getNodeCharsetFromResponse, iconv, isGzipError, passthruStream, reqNeedsBasicAuthHeaders, responseMustHaveEmptyBody, rewriter, setCookie, zlib, zlibOptions,
3    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
4
5  _ = require("lodash");
6
7  zlib = require("zlib");
8
9  charset = require("charset");
10
11  concat = require("concat-stream");
12
13  iconv = require("iconv-lite");
14
15  Promise = require("bluebird");
16
17  accept = require("http-accept");
18
19  debug = require("debug")("cypress:server:proxy");
20
21  cwd = require("../cwd");
22
23  cors = require("../util/cors");
24
25  buffers = require("../util/buffers");
26
27  rewriter = require("../util/rewriter");
28
29  blacklist = require("../util/blacklist");
30
31  conditional = require("../util/conditional_stream");
32
33  passthruStream = require("../util/passthru_stream").passthruStream;
34
35  REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308];
36
37  NO_BODY_STATUS_CODES = [204, 304];
38
39  zlib = Promise.promisifyAll(zlib);
40
41  zlibOptions = {
42    flush: zlib.Z_SYNC_FLUSH,
43    finishFlush: zlib.Z_SYNC_FLUSH
44  };
45
46  getNodeCharsetFromResponse = function(headers, body) {
47    var httpCharset;
48    httpCharset = (charset(headers, body, 1024) || '').toLowerCase();
49    debug("inferred charset from response %o", {
50      httpCharset: httpCharset
51    });
52    if (iconv.encodingExists(httpCharset)) {
53      return httpCharset;
54    }
55    return "latin1";
56  };
57
58  isGzipError = function(err) {
59    return Object.prototype.hasOwnProperty.call(zlib.constants, err.code);
60  };
61
62  responseMustHaveEmptyBody = function(method, statusCode) {
63    return _.some([_.includes(NO_BODY_STATUS_CODES, statusCode), _.invoke(method, 'toLowerCase') === 'head']);
64  };
65
66  setCookie = function(res, key, val, domainName) {
67    var options;
68    options = {
69      domain: domainName
70    };
71    if (!val) {
72      val = "";
73      options.expires = new Date(0);
74    }
75    return res.cookie(key, val, options);
76  };
77
78  reqNeedsBasicAuthHeaders = function(req, remoteState) {
79    var auth, origin;
80    auth = remoteState.auth, origin = remoteState.origin;
81    return auth && !req.headers["authorization"] && cors.urlMatchesOriginProtectionSpace(req.proxiedUrl, origin);
82  };
83
84  module.exports = {
85    handle: function(req, res, config, getRemoteState, request, nodeProxy) {
86      var blh, matched, remoteState, thr;
87      remoteState = getRemoteState();
88      debug("handling proxied request %o", {
89        url: req.url,
90        proxiedUrl: req.proxiedUrl,
91        headers: req.headers,
92        remoteState: remoteState
93      });
94      if (req.cookies["__cypress.unload"]) {
95        return res.redirect(config.clientRoute);
96      }
97      if (req.url === req.proxiedUrl && !remoteState.visiting) {
98        return res.redirect(config.clientRoute);
99      }
100      if (blh = config.blacklistHosts) {
101        if (matched = blacklist.matches(req.proxiedUrl, blh)) {
102          res.set("x-cypress-matched-blacklisted-host", matched);
103          debug("blacklisting request %o", {
104            url: req.proxiedUrl,
105            matched: matched
106          });
107          return res.status(503).end();
108        }
109      }
110      thr = passthruStream();
111      return this.getHttpContent(thr, req, res, remoteState, config, request).pipe(res);
112    },
113    getHttpContent: function(thr, req, res, remoteState, config, request) {
114      var auth, base64, encodings, endWithNetworkErr, isInitial, obj, onResponse, opts, ref, reqAcceptsHtml, resContentTypeIs, resContentTypeIsJavaScript, resMatchesOriginPolicy, rq, setBody, setCookies, wantsInjection, wantsSecurityRemoved;
115      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
116      isInitial = req.cookies["__cypress.initial"] === "true";
117      wantsInjection = null;
118      wantsSecurityRemoved = null;
119      resContentTypeIs = function(respHeaders, str) {
120        var contentType;
121        contentType = respHeaders["content-type"];
122        return contentType && contentType.includes(str);
123      };
124      resContentTypeIsJavaScript = function(respHeaders) {
125        return _.some(['application/javascript', 'application/x-javascript', 'text/javascript'].map(_.partial(resContentTypeIs, respHeaders)));
126      };
127      reqAcceptsHtml = function() {
128        var find, ref, types;
129        if (req.headers["x-requested-with"]) {
130          return;
131        }
132        types = (ref = accept.parser(req.headers.accept)) != null ? ref : [];
133        find = function(type) {
134          return indexOf.call(types, type) >= 0;
135        };
136        return find("text/html") && find("application/xhtml+xml");
137      };
138      resMatchesOriginPolicy = function(respHeaders) {
139        switch (remoteState.strategy) {
140          case "http":
141            return cors.urlMatchesOriginPolicyProps(req.proxiedUrl, remoteState.props);
142          case "file":
143            return req.proxiedUrl.startsWith(remoteState.origin);
144        }
145      };
146      setCookies = function(value) {
147        if ((!value) && (!wantsInjection)) {
148          return;
149        }
150        if (!isInitial) {
151          return;
152        }
153        return setCookie(res, "__cypress.initial", value, remoteState.domainName);
154      };
155      setBody = function(str, statusCode, headers) {
156        var encoding, gunzip, injection, isGzipped, onError, rewrite;
157        res.status(statusCode);
158        setCookies(false, wantsInjection);
159        encoding = headers["content-encoding"];
160        isGzipped = encoding && encoding.includes("gzip");
161        debug("received response for %o", {
162          url: req.proxiedUrl,
163          headers: headers,
164          statusCode: statusCode,
165          isGzipped: isGzipped,
166          wantsInjection: wantsInjection,
167          wantsSecurityRemoved: wantsSecurityRemoved
168        });
169        if (responseMustHaveEmptyBody(req.method, statusCode)) {
170          return res.end();
171        }
172        if (wantsInjection) {
173          rewrite = function(body) {
174            var decodedBody, nodeCharset, rewrittenBody;
175            nodeCharset = getNodeCharsetFromResponse(headers, body);
176            decodedBody = iconv.decode(body, nodeCharset);
177            rewrittenBody = rewriter.html(decodedBody, remoteState.domainName, wantsInjection, wantsSecurityRemoved);
178            return iconv.encode(rewrittenBody, nodeCharset);
179          };
180          injection = concat(function(body) {
181            if (_.isEqual(body, [])) {
182              body = Buffer.from('');
183            }
184            if (isGzipped) {
185              return zlib.gunzipAsync(body, zlibOptions).then(rewrite).then(zlib.gzipAsync).then(thr.end)["catch"](endWithNetworkErr);
186            } else {
187              return thr.end(rewrite(body));
188            }
189          });
190          return str.pipe(injection);
191        } else {
192          if (wantsSecurityRemoved) {
193            gunzip = zlib.createGunzip(zlibOptions);
194            gunzip.setEncoding("utf8");
195            onError = function(err) {
196              var gzipError;
197              gzipError = isGzipError(err);
198              debug("failed to proxy response %o", {
199                url: req.proxiedUrl,
200                headers: headers,
201                statusCode: statusCode,
202                isGzipped: isGzipped,
203                gzipError: gzipError,
204                wantsInjection: wantsInjection,
205                wantsSecurityRemoved: wantsSecurityRemoved,
206                err: err
207              });
208              return endWithNetworkErr(err);
209            };
210            return str.pipe(conditional(isGzipped, gunzip)).on("error", onError).pipe(rewriter.security()).on("error", onError).pipe(conditional(isGzipped, zlib.createGzip())).on("error", onError).pipe(thr).on("error", onError);
211          }
212          return str.pipe(thr);
213        }
214      };
215      endWithNetworkErr = function(err) {
216        debug('request failed in proxy layer %o', {
217          res: _.pick(res, 'headersSent', 'statusCode', 'headers'),
218          req: _.pick(req, 'url', 'proxiedUrl', 'headers', 'method'),
219          err: err
220        });
221        return req.socket.destroy();
222      };
223      onResponse = (function(_this) {
224        return function(str, incomingRes) {
225          var c, cookies, err, headers, i, len, newUrl, originalSetHeader, ref, statusCode;
226          headers = incomingRes.headers, statusCode = incomingRes.statusCode;
227          originalSetHeader = res.setHeader;
228          res.setHeader = function(k, v) {
229            if (k === 'content-type') {
230              v = incomingRes.headers['content-type'];
231            }
232            return originalSetHeader.call(res, k, v);
233          };
234          if (wantsInjection == null) {
235            wantsInjection = (function() {
236              if (!resContentTypeIs(headers, "text/html")) {
237                return false;
238              }
239              if (!resMatchesOriginPolicy(headers)) {
240                return false;
241              }
242              if (isInitial) {
243                return "full";
244              }
245              if (!reqAcceptsHtml()) {
246                return false;
247              }
248              return "partial";
249            })();
250          }
251          wantsSecurityRemoved = (function() {
252            return config.modifyObstructiveCode && ((wantsInjection === "full") || resContentTypeIsJavaScript(headers));
253          })();
254          _this.setResHeaders(req, res, incomingRes, wantsInjection);
255          if (cookies = headers["set-cookie"]) {
256            ref = [].concat(cookies);
257            for (i = 0, len = ref.length; i < len; i++) {
258              c = ref[i];
259              try {
260                res.append("Set-Cookie", c);
261              } catch (error) {
262                err = error;
263              }
264            }
265          }
266          if (REDIRECT_STATUS_CODES.includes(statusCode)) {
267            newUrl = headers.location;
268            setCookies(true);
269            debug("redirecting to new url %o", {
270              status: statusCode,
271              url: newUrl
272            });
273            return res.redirect(statusCode, newUrl);
274          }
275          if (headers["x-cypress-file-server-error"]) {
276            wantsInjection || (wantsInjection = "partial");
277          }
278          return setBody(str, statusCode, headers);
279        };
280      })(this);
281      if (obj = buffers.take(req.proxiedUrl)) {
282        wantsInjection = "full";
283        onResponse(obj.stream, obj.response);
284      } else {
285        opts = {
286          timeout: null,
287          strictSSL: false,
288          followRedirect: false,
289          retryIntervals: [0, 100, 200, 200]
290        };
291        encodings = (ref = accept.parser(req.headers["accept-encoding"])) != null ? ref : [];
292        if (indexOf.call(encodings, "gzip") >= 0) {
293          req.headers["accept-encoding"] = "gzip";
294        } else {
295          delete req.headers["accept-encoding"];
296        }
297        if (remoteState.strategy === "file" && req.proxiedUrl.startsWith(remoteState.origin)) {
298          opts.url = req.proxiedUrl.replace(remoteState.origin, remoteState.fileServer);
299        } else {
300          opts.url = req.proxiedUrl;
301        }
302        if (reqNeedsBasicAuthHeaders(req, remoteState)) {
303          auth = remoteState.auth;
304          base64 = Buffer.from(auth.username + ":" + auth.password).toString("base64");
305          req.headers["authorization"] = "Basic " + base64;
306        }
307        rq = request.create(opts);
308        rq.on("error", endWithNetworkErr);
309        rq.on("response", function(incomingRes) {
310          return onResponse(rq, incomingRes);
311        });
312        req.on("aborted", function() {
313          return rq.abort();
314        });
315        req.pipe(rq);
316      }
317      return thr;
318    },
319    setResHeaders: function(req, res, incomingRes, wantsInjection) {
320      var headers;
321      if (res.headersSent) {
322        return;
323      }
324      headers = _.omit(incomingRes.headers, "set-cookie", "x-frame-options", "content-length", "content-security-policy", "connection");
325      if (wantsInjection) {
326        headers["cache-control"] = "no-cache, no-store, must-revalidate";
327      }
328      return res.set(headers);
329    }
330  };
331
332}).call(this);
333
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)