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

index.js

Source: index.js Github

copy
1module.exports.init = function(config, logger, stats) {
2
3    return {
4      // indicates start of client request
5      onrequest: function(req, res, next) {
6        console.log('---> onrequest()');
7        if(req.headers['static-response'] == 'true') {
8          sendStaticResponse(req, res, next);
9        }
10        else {
11          next();
12        }
13      },
14      
15      // chunk of request payload data received from client
16      ondata_request: function(req, res, data, next) {
17        console.log('---> ondata_request()');
18        next(null, data);
19      },
20  
21      // last chunk of request payload data received from client
22      onend_request: function(req, res, data, next) {
23        console.log('---> onend_request()');
24        next(null, data);
25      },
26  
27      // indicates start of target response
28      onresponse: function(req, res, next) {
29        console.log('---> onresponse()');
30        next();
31      },
32  
33      // a chunk of response payload data received from target
34      ondata_response: function(req, res, data, next) {
35        console.log('---> ondata_response()');
36        next(null, data);
37      },
38  
39      // last chunk of response payload data received from target
40      onend_response: function(req, res, data, next) {
41        console.log('---> onend_response()');
42        next(null, data);
43      }
44    };
45  }
46
47function sendStaticResponse(req, res, next) {
48    var response = {
49        type: 'INFO',
50        message: 'This is a static response'
51    };
52
53    if (!res.finished) res.setHeader('content-type', 'application/json');
54    res.end(JSON.stringify(response));
55}
Full Screen

driver-events.js

Source: driver-events.js Github

copy
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4    return new (P || (P = Promise))(function (resolve, reject) {
5        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8        step((generator = generator.apply(thisArg, _arguments || [])).next());
9    });
10};
11var __importDefault = (this && this.__importDefault) || function (mod) {
12    return (mod && mod.__esModule) ? mod : { "default": mod };
13};
14Object.defineProperty(exports, "__esModule", { value: true });
15exports.onNetStubbingEvent = exports._restoreMatcherOptionsTypes = void 0;
16const lodash_1 = __importDefault(require("lodash"));
17const debug_1 = __importDefault(require("debug"));
18const types_1 = require("../types");
19const util_1 = require("./util");
20const intercepted_request_1 = require("./intercepted-request");
21const debug = (0, debug_1.default)('cypress:net-stubbing:server:driver-events');
22function onRouteAdded(state, getFixture, options) {
23    return __awaiter(this, void 0, void 0, function* () {
24        const routeMatcher = _restoreMatcherOptionsTypes(options.routeMatcher);
25        const { staticResponse } = options;
26        if (staticResponse) {
27            yield (0, util_1.setResponseFromFixture)(getFixture, staticResponse);
28        }
29        const route = {
30            id: options.routeId,
31            hasInterceptor: options.hasInterceptor,
32            staticResponse: options.staticResponse,
33            routeMatcher,
34            getFixture,
35            matches: 0,
36        };
37        state.routes.push(route);
38    });
39}
40function getRequest(state, requestId) {
41    return Object.values(state.requests).find(({ id }) => {
42        return requestId === id;
43    });
44}
45function subscribe(state, options) {
46    const request = getRequest(state, options.requestId);
47    if (!request) {
48        return;
49    }
50    request.addSubscription(options.subscription);
51}
52function sendStaticResponse(state, getFixture, options) {
53    return __awaiter(this, void 0, void 0, function* () {
54        const request = getRequest(state, options.requestId);
55        if (!request) {
56            return;
57        }
58        if (options.staticResponse.fixture && ['before:response', 'response:callback', 'response'].includes(request.lastEvent)) {
59            // if we're already in a response phase, it's possible that the fixture body will never be sent to the browser
60            // so include the fixture body in `after:response`
61            request.includeBodyInAfterResponse = true;
62        }
63        yield (0, util_1.setResponseFromFixture)(getFixture, options.staticResponse);
64        yield (0, util_1.sendStaticResponse)(request, options.staticResponse);
65    });
66}
67function _restoreMatcherOptionsTypes(options) {
68    const stringMatcherFields = (0, util_1.getAllStringMatcherFields)(options);
69    const ret = {};
70    stringMatcherFields.forEach((field) => {
71        const obj = lodash_1.default.get(options, field);
72        if (!obj) {
73            return;
74        }
75        let { value, type } = obj;
76        if (type === 'regex') {
77            const lastSlashI = value.lastIndexOf('/');
78            const flags = value.slice(lastSlashI + 1);
79            const pattern = value.slice(1, lastSlashI);
80            value = new RegExp(pattern, flags);
81        }
82        lodash_1.default.set(ret, field, value);
83    });
84    lodash_1.default.extend(ret, lodash_1.default.pick(options, types_1.PLAIN_FIELDS));
85    return ret;
86}
87exports._restoreMatcherOptionsTypes = _restoreMatcherOptionsTypes;
88function onNetStubbingEvent(opts) {
89    return __awaiter(this, void 0, void 0, function* () {
90        const { state, getFixture, args, eventName, frame } = opts;
91        debug('received driver event %o', { eventName, args });
92        switch (eventName) {
93            case 'route:added':
94                return onRouteAdded(state, getFixture, frame);
95            case 'subscribe':
96                return subscribe(state, frame);
97            case 'event:handler:resolved':
98                return intercepted_request_1.InterceptedRequest.resolveEventHandler(state, frame);
99            case 'send:static:response':
100                return sendStaticResponse(state, getFixture, frame);
101            default:
102                throw new Error(`Unrecognized net event: ${eventName}`);
103        }
104    });
105}
106exports.onNetStubbingEvent = onNetStubbingEvent;
107
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)