How to use this.requestLib 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.

Calculadora.js

Source: Calculadora.js Github

copy
1
2class Calculadora {
3
4    constructor(number, requestLib) {
5        this.value = number;
6        this.requestLib = requestLib;
7    }
8
9    sum(value) {
10        this.value += value;
11    }
12
13    result() {
14        return this.value;
15    }
16
17    sub(value) {
18        this.value -= value;
19    }
20
21    expression(fn) {
22        this.value = fn(this.value);
23    }
24
25    readData() {
26        return this.requestLib.get("http://teste.com.br/jao");
27    }
28
29}
30
31module.exports = { Calculadora };
Full Screen

simple-proxy.js

Source: simple-proxy.js Github

copy
1/* eslint-disable no-console */
2/* eslint-disable class-methods-use-this */
3/* eslint-disable no-param-reassign */
4
5const url = require('url');
6const http = require('http');
7const https = require('https');
8const events = require('events');
9
10class Proxy extends events.EventEmitter {
11  constructor(proxyURI, options = {}) {
12    super();
13    this.logging = options.logging != null ? options.logging : false;
14    this.timeout = options.timeout != null ? options.timeout : 0;
15    this.agent = options.agent != null ? options.agent : undefined;
16    this.preserveHost =
17      options.preserveHost != null ? options.preserveHost : false;
18    this.rejectUnauthorized =
19      options.rejectUnauthorized != null ? options.rejectUnauthorized : true;
20
21    const { protocol, hostname, port, pathname } = url.parse(proxyURI);
22
23    this.protocol = protocol;
24    this.hostname = hostname;
25    this.port = port;
26
27    // We concatenate with req.url later; no trailing slash is desired:
28    this.pathname = pathname.replace(/\/$/, '');
29
30    if (this.protocol === 'https:') {
31      this.requestLib = https;
32      if (!this.port) {
33        this.port = 443;
34      }
35    } else if (this.protocol === 'http:') {
36      this.requestLib = http;
37      if (!this.port) {
38        this.port = 80;
39      }
40    } else {
41      throw new Error(`Unsupported protocol: ${this.protocol}`);
42    }
43  }
44
45  server(req, res) {
46    const options = {
47      host: this.hostname,
48      path: this.pathname + req.url,
49      port: this.port,
50      method: req.method,
51      headers: req.headers,
52      agent: this.agent,
53      rejectUnauthorized: this.rejectUnauthorized,
54    };
55
56    if (!this.preserveHost) {
57      options.headers.host = this.hostname;
58    }
59
60    const proxyRequest = this.requestLib.request(options, proxyResponse =>
61      this.onProxyResponse(proxyResponse, res, options),
62    );
63
64    if (this.timeout) {
65      proxyRequest.setTimeout(this.timeout, error => {
66        error = `Request timed out after ${this.timeout} ms.`;
67        this.emit('proxyTimeout', error, options);
68        this.onProxyTimeout(error, options, res);
69        proxyRequest.abort();
70      });
71    }
72
73    proxyRequest.on('error', error => {
74      this.emit('proxyError', error, options);
75      this.onProxyError(error, options, res);
76    });
77
78    if (req.headers['content-length']) {
79      this.processRequestData(proxyRequest, req, options);
80    } else {
81      proxyRequest.end();
82    }
83  }
84
85  processRequestData(proxyRequest, req, options) {
86    let requestData = '';
87
88    req.on('data', chunk => {
89      requestData += chunk;
90      proxyRequest.write(chunk, 'binary');
91    });
92
93    req.on('end', () => {
94      this.emit('requestEnd', requestData, options);
95      proxyRequest.end();
96    });
97  }
98
99  onProxyResponse(proxyResponse, res, options) {
100    res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
101    let responseData = '';
102
103    proxyResponse.on('data', chunk => {
104      responseData += chunk;
105      res.write(chunk, 'binary');
106    });
107
108    proxyResponse.on('end', () => {
109      if (this.logging) {
110        console.error(`Proxy end: ${responseData}`);
111      }
112      this.emit('proxyResponse', responseData, options);
113      res.end();
114    });
115  }
116
117  onProxyTimeout(err, options, res) {
118    if (this.logging) {
119      console.error(`Proxy timeout: ${err}`);
120    }
121    res.writeHead(504, 'Gateway Timeout');
122    res.end();
123  }
124
125  onProxyError(err, options, res) {
126    if (this.logging) {
127      console.error(`Proxy error: ${err}, ${JSON.stringify(options)}`);
128    }
129    res.writeHead(502, 'Bad Gateway');
130    res.end();
131  }
132}
133
134function proxyPass(proxyURI, options = {}) {
135  const p = new Proxy(proxyURI, options);
136
137  return p.server.bind(p);
138}
139
140module.exports = {
141  proxyPass,
142  Proxy,
143};
144
Full Screen

api.js

Source: api.js Github

copy
1const Asset = require("./common/asset");
2const AssetProperties = require('./common/assetproperties');
3const Report = require("./common/report");
4const Tools = require("./common/tools");
5const Util = require("./common/util");
6const Workflow = require("./common/workflow");
7
8const apiErrors = {
9    InstanceNameInvalid: 1
10}
11
12/********************************************
13 * Javascript API for utilizing the crownpeak API
14 * All function are asyncronous and are operated upon by
15 * promises
16 *
17 ********************************************/
18class api {
19
20    constructor() {
21        this.host;
22        this.instance;
23        this.apiKey;
24        this._isAuthenticated = false;
25        this._error;
26        this.cookie;
27        this.https = require("https");
28        this.requestLib = require('request-promise');
29        this.webAPIRoot = "/cpt_webservice/accessapi/";
30        this.Asset = new Asset(this);
31        this.AssetProperties = new AssetProperties(this);
32        this.Report = new Report(this);
33        this.Tools = new Tools(this);
34        this.Workflow = new Workflow(this);
35    }
36
37
38    get isAuthenticated() {
39        return this._isAuthenticated;
40    }
41
42    get error() {
43        return this._error;
44    }
45
46
47    /**
48     * Authenticate the user such that all other function can run
49     * @param {string} username - The username of the user
50     * @param {string} password - The password of the user
51     * @param {string} host - The host of the user
52     * @param {string} instance
53     * @param {string} apiKey
54     */
55    async login(username, password, host, instance, apiKey) {
56        this.host = host;
57        this.instance = instance;
58        this.apiKey = apiKey;
59        var apiParent = this;
60        var parentResponse; //Store the response for return of the await
61        var parentError; //Store the error
62        var authJson = {
63            "instance": instance,
64            "username": username,
65            "password": password,
66            "remember_me": "false",
67            "timeZoneOffsetMinutes": "-480"
68        };
69
70
71        await this.postRequest("/Auth/Authenticate", authJson,
72            function(response) {
73                parentResponse = response;
74            },
75            function(error) {
76                parentError = error;
77            });
78
79
80        if (parentResponse !== undefined && Util.IsValidJSONString(parentResponse.body)) {
81            var jsonBody = JSON.parse(parentResponse.body);
82            if (jsonBody.resultCode === Util.ResponseMessages.Success) {
83                //User was successfully authenticated
84                this._isAuthenticated = true;
85                this.cookie = parentResponse.headers["set-cookie"];
86            } else {
87                this._error = parentResponse;
88            }
89        } else {
90            if (parentError !== undefined && Util.IsValidJSONString(parentError.error)) {
91                this._error = parentError;
92                throw parentError;
93            }
94            throw Error("Unable to contact CMS, please check your settings");
95        }
96
97        return parentResponse;
98    }
99
100
101    static currentDate() {
102        var today = new Date();
103        var dd = String(today.getDate()).padStart(2, '0');
104        var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
105        var yyyy = today.getFullYear();
106
107        return mm + '/' + dd + '/' + yyyy;
108
109    }
110
111    /**
112     *
113     * @param {string} urlPath - The path to call from the url
114     * @param {JSON|string} data - The data to send in the request
115     * @param {function(object)} callback - function to run on succes
116     * @param {function(object)} onError - function to run on error
117     */
118    async postRequest(urlPath, data, callback, onError) {
119        var currentAPI = this;
120        var attempt = 0;
121
122        if (urlPath.startsWith("/")) {
123            urlPath = urlPath.substring(1, urlPath.length);
124        }
125
126
127
128        const options = {
129            url: "https://" + this.host + "/" + this.instance + this.webAPIRoot + urlPath, //URL of the instance
130            headers: {
131                'x-api-key': this.apiKey, //The API Key
132                'accept': 'application/json', //Data is returned in JSON format
133                'Content-Type': 'text/json', //Data is sent in JSON format
134                'cp-datetime': api.currentDate() //The current datetime
135            },
136            body: JSON.stringify(data),
137            //proxy: "http://127.0.0.1:8888",
138            resolveWithFullResponse: true,
139            method: "POST"
140        }
141
142        if (this._isAuthenticated) {
143            options.headers.cookie = this.cookie;
144        }
145        try {
146            var response = await this.requestLib.post(options);
147            callback(response);
148        } catch (error) {
149            var timeoutWait = Util.InitialTimeoutWait;
150
151            if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {
152                attempt++;
153                /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,
154                otherwise use the time given  */
155                if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {
156                    var retryAfter = parseInt(error.response.headers["retry-after"], 10);
157                    if (retryAfter != "NaN") {
158                        timeoutWait = retryAfter * 1000;
159                    }
160                }
161                await Util.timeout(timeoutWait);
162                await currentAPI.postRequest(urlPath, data, callback, onError);
163            } else {
164                if (onError !== undefined) {
165                    onError(error);
166                }
167
168            }
169        }
170    }
171
172    /**
173     *
174     * @param {string} urlPath - The path to call from the url
175     * @param {function(object)} callback - function to run on success
176     * @param {function(object)=} onError - function to run on error
177     */
178    async getCmsRequest(urlPath, callback, onError) {
179        var currentAPI = this;
180        var attempt = 0;
181
182        if (urlPath.startsWith("/")) {
183            urlPath = urlPath.substring(1, urlPath.length);
184        }
185
186        const options = {
187            url: "https://" + this.host + "/" + urlPath, //URL of the instance
188            headers: {},
189            resolveWithFullResponse: true,
190            method: "GET",
191            encoding: null
192        }
193
194        if (this._isAuthenticated) {
195            options.headers.cookie = this.cookie;
196        }
197        try {
198            var response = await this.requestLib.get(options);
199            callback(response);
200        } catch (error) {
201            var timeoutWait = Util.InitialTimeoutWait;
202
203            if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {
204                attempt++;
205                /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,
206                otherwise use the time given  */
207                if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {
208                    var retryAfter = parseInt(error.response.headers["retry-after"], 10);
209                    if (retryAfter != "NaN") {
210                        timeoutWait = retryAfter * 1000;
211                    }
212                }
213                await Util.timeout(timeoutWait);
214                await currentAPI.getCmsRequest(urlPath, callback, onError);
215            } else {
216                if (onError !== undefined) {
217                    onError(error);
218                }
219
220            }
221        }
222    }
223
224
225    /**
226     *
227     * @param {string} urlPath - The path to call from the url
228     * @param {JSON|string} data - The data to send in the request
229     * @param {function(object)} callback - function to run on succes
230     * @param {function(object)} onError - function to run on error
231     */
232    postRequestV1(urlPath, data, callback, onError) {
233        var currentAPI = this;
234        var attempt = 0;
235
236        if (urlPath.startsWith("/")) {
237            urlPath = urlPath.substring(1, urlPath.length);
238        }
239
240
241        const options = {
242            url: "https://" + this.host + "/" + this.instance + this.webAPIRoot + urlPath, //URL of the instance
243            headers: {
244                'x-api-key': this.apiKey, //The API Key
245                'accept': 'application/json', //Data is returned in JSON format
246                'Content-Type': 'text/json', //Data is sent in JSON format
247                'cp-datetime': api.currentDate() //The current datetime
248            },
249            body: JSON.stringify(data),
250            //proxy: "http://127.0.0.1:8888",
251            resolveWithFullResponse: true,
252            method: "POST"
253        }
254
255        if (this._isAuthenticated) {
256            options.headers.cookie = this.cookie;
257        }
258        return this.requestLib.post(options).then(callback).catch(
259            function(error) {
260                var timeoutWait = Util.InitialTimeoutWait;
261
262                if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {
263                    attempt++;
264                    /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,
265                    otherwise use the time given  */
266                    if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {
267                        var retryAfter = parseInt(error.response.headers["retry-after"], 10);
268                        if (retryAfter != "NaN") {
269                            timeoutWait = retryAfter * 1000;
270                        }
271                    }
272                    setTimeout(currentAPI.postRequest(urlPath, data, callback, onError), timeoutWait);
273                } else {
274                    if (onError !== undefined) {
275                        onError(error);
276                    }
277                }
278
279
280
281            }
282        );
283    }
284
285    Asset = Asset;
286    AssetProperties = AssetProperties;
287    Report = Report;
288    Tools = Tools;
289    Util = Util;
290    Workflow = Workflow;
291}
292
293module.exports = api;
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)