How to use createInitialWorkers method in Cypress

Best JavaScript code snippet using cypress

server.js

Source:server.js Github

copy

Full Screen

...169        return this._getRemoteState()170      }171      this.createNetworkProxy(config, getRemoteState)172      if (config.experimentalSourceRewriting) {173        createInitialWorkers()174      }175      this.createHosts(config.hosts)176      this.createRoutes({177        app,178        config,179        getRemoteState,180        networkProxy: this._networkProxy,181        onError,182        project,183      })184      return this.createServer(app, config, project, this._request, onWarning)185    })186  }187  createNetworkProxy (config, getRemoteState) {...

Full Screen

Full Screen

server-base.js

Source:server-base.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.ServerBase = void 0;4const tslib_1 = require("tslib");5require("./cwd");6const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));7const compression_1 = (0, tslib_1.__importDefault)(require("compression"));8const debug_1 = (0, tslib_1.__importDefault)(require("debug"));9const evil_dns_1 = (0, tslib_1.__importDefault)(require("evil-dns"));10const express_1 = (0, tslib_1.__importDefault)(require("express"));11const http_1 = (0, tslib_1.__importDefault)(require("http"));12const http_proxy_1 = (0, tslib_1.__importDefault)(require("http-proxy"));13const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));14const url_1 = (0, tslib_1.__importDefault)(require("url"));15const lazy_ass_1 = (0, tslib_1.__importDefault)(require("lazy-ass"));16const net_stubbing_1 = require("../../net-stubbing");17const network_1 = require("../../network");18const proxy_1 = require("../../proxy");19const errors_1 = (0, tslib_1.__importDefault)(require("./errors"));20const logger_1 = (0, tslib_1.__importDefault)(require("./logger"));21const request_1 = (0, tslib_1.__importDefault)(require("./request"));22const template_engine_1 = (0, tslib_1.__importDefault)(require("./template_engine"));23const class_helpers_1 = require("./util/class-helpers");24const origin_1 = (0, tslib_1.__importDefault)(require("./util/origin"));25const server_destroy_1 = require("./util/server_destroy");26const socket_allowed_1 = require("./util/socket_allowed");27const rewriter_1 = require("../../rewriter");28const routes_1 = require("./routes");29const routes_e2e_1 = require("./routes-e2e");30const routes_ct_1 = require("./routes-ct");31const ALLOWED_PROXY_BYPASS_URLS = [32    '/',33    '/__cypress/runner/cypress_runner.css',34    '/__cypress/runner/cypress_runner.js',35    '/__cypress/runner/favicon.ico',36];37const DEFAULT_DOMAIN_NAME = 'localhost';38const fullyQualifiedRe = /^https?:\/\//;39const debug = (0, debug_1.default)('cypress:server:server-base');40const _isNonProxiedRequest = (req) => {41    // proxied HTTP requests have a URL like: "http://example.com/foo"42    // non-proxied HTTP requests have a URL like: "/foo"43    return req.proxiedUrl.startsWith('/');44};45const _forceProxyMiddleware = function (clientRoute) {46    // normalize clientRoute to help with comparison47    const trimmedClientRoute = lodash_1.default.trimEnd(clientRoute, '/');48    return function (req, res, next) {49        const trimmedUrl = lodash_1.default.trimEnd(req.proxiedUrl, '/');50        if (_isNonProxiedRequest(req) && !ALLOWED_PROXY_BYPASS_URLS.includes(trimmedUrl) && (trimmedUrl !== trimmedClientRoute)) {51            // this request is non-proxied and non-allowed, redirect to the runner error page52            return res.redirect(clientRoute);53        }54        return next();55    };56};57const setProxiedUrl = function (req) {58    // proxiedUrl is the full URL with scheme, host, and port59    // it will only be fully-qualified if the request was proxied.60    // this function will set the URL of the request to be the path61    // only, which can then be used to proxy the request.62    // bail if we've already proxied the url63    if (req.proxiedUrl) {64        return;65    }66    // backup the original proxied url67    // and slice out the host/origin68    // and only leave the path which is69    // how browsers would normally send70    // use their url71    req.proxiedUrl = network_1.uri.removeDefaultPort(req.url).format();72    req.url = network_1.uri.getPath(req.url);73};74const notSSE = (req, res) => {75    return (req.headers.accept !== 'text/event-stream') && compression_1.default.filter(req, res);76};77class ServerBase {78    constructor() {79        this.ensureProp = class_helpers_1.ensureProp;80        this.isListening = false;81        // @ts-ignore82        this.request = (0, request_1.default)();83        this.socketAllowed = new socket_allowed_1.SocketAllowed();84        this._middleware = null;85        this._baseUrl = null;86        this._fileServer = null;87    }88    get server() {89        return this.ensureProp(this._server, 'open');90    }91    get socket() {92        return this.ensureProp(this._socket, 'open');93    }94    get nodeProxy() {95        return this.ensureProp(this._nodeProxy, 'open');96    }97    get networkProxy() {98        return this.ensureProp(this._networkProxy, 'open');99    }100    get netStubbingState() {101        return this.ensureProp(this._netStubbingState, 'open');102    }103    get httpsProxy() {104        return this.ensureProp(this._httpsProxy, 'open');105    }106    open(config, { getSpec, getCurrentBrowser, onError, onWarning, shouldCorrelatePreRequests, specsStore, testingType, SocketCtor, exit, }) {107        debug('server open');108        (0, lazy_ass_1.default)(lodash_1.default.isPlainObject(config), 'expected plain config object', config);109        return bluebird_1.default.try(() => {110            if (!config.baseUrl && testingType === 'component') {111                throw new Error('ServerCt#open called without config.baseUrl.');112            }113            const app = this.createExpressApp(config);114            logger_1.default.setSettings(config);115            this._nodeProxy = http_proxy_1.default.createProxyServer({116                target: config.baseUrl && testingType === 'component' ? config.baseUrl : undefined,117            });118            this._socket = new SocketCtor(config);119            network_1.clientCertificates.loadClientCertificateConfig(config);120            const getRemoteState = () => {121                return this._getRemoteState();122            };123            this.createNetworkProxy(config, getRemoteState, shouldCorrelatePreRequests);124            if (config.experimentalSourceRewriting) {125                (0, rewriter_1.createInitialWorkers)();126            }127            this.createHosts(config.hosts);128            const routeOptions = {129                config,130                specsStore,131                getRemoteState,132                nodeProxy: this.nodeProxy,133                networkProxy: this._networkProxy,134                onError,135                getSpec,136                getCurrentBrowser,137                testingType,138                exit,139            };140            const runnerSpecificRouter = testingType === 'e2e'141                ? (0, routes_e2e_1.createRoutesE2E)(routeOptions)142                : (0, routes_ct_1.createRoutesCT)(routeOptions);143            app.use(runnerSpecificRouter);144            app.use((0, routes_1.createCommonRoutes)(routeOptions));145            return this.createServer(app, config, onWarning);146        });147    }148    createExpressApp(config) {149        const { morgan, clientRoute } = config;150        const app = (0, express_1.default)();151        // set the cypress config from the cypress.json file152        app.set('view engine', 'html');153        // since we use absolute paths, configure express-handlebars to not automatically find layouts154        // https://github.com/cypress-io/cypress/issues/2891155        app.engine('html', template_engine_1.default.render);156        // handle the proxied url in case157        // we have not yet started our websocket server158        app.use((req, res, next) => {159            setProxiedUrl(req);160            // useful for tests161            if (this._middleware) {162                this._middleware(req, res);163            }164            // always continue on165            return next();166        });167        app.use(_forceProxyMiddleware(clientRoute));168        app.use(require('cookie-parser')());169        app.use((0, compression_1.default)({ filter: notSSE }));170        if (morgan) {171            app.use(require('morgan')('dev'));172        }173        // errorhandler174        app.use(require('errorhandler')());175        // remove the express powered-by header176        app.disable('x-powered-by');177        return app;178    }179    getHttpServer() {180        return this._server;181    }182    portInUseErr(port) {183        const e = errors_1.default.get('PORT_IN_USE_SHORT', port);184        e.port = port;185        e.portInUse = true;186        return e;187    }188    createNetworkProxy(config, getRemoteState, shouldCorrelatePreRequests) {189        const getFileServerToken = () => {190            return this._fileServer.token;191        };192        this._netStubbingState = (0, net_stubbing_1.netStubbingState)();193        // @ts-ignore194        this._networkProxy = new proxy_1.NetworkProxy({195            config,196            shouldCorrelatePreRequests,197            getRemoteState,198            getFileServerToken,199            socket: this.socket,200            netStubbingState: this.netStubbingState,201            request: this.request,202        });203    }204    startWebsockets(automation, config, options = {}) {205        var _a;206        options.onRequest = this._onRequest.bind(this);207        options.netStubbingState = this.netStubbingState;208        options.getRenderedHTMLOrigins = (_a = this._networkProxy) === null || _a === void 0 ? void 0 : _a.http.getRenderedHTMLOrigins;209        options.onResetServerState = () => {210            this.networkProxy.reset();211            this.netStubbingState.reset();212        };213        const io = this.socket.startListening(this.server, automation, config, options);214        this._normalizeReqUrl(this.server);215        return io;216    }217    createHosts(hosts = []) {218        return lodash_1.default.each(hosts, (ip, host) => {219            return evil_dns_1.default.add(host, ip);220        });221    }222    addBrowserPreRequest(browserPreRequest) {223        this.networkProxy.addPendingBrowserPreRequest(browserPreRequest);224    }225    emitRequestEvent(eventName, data) {226        this.socket.toDriver('request:event', eventName, data);227    }228    _createHttpServer(app) {229        const svr = http_1.default.createServer(network_1.httpUtils.lenientOptions, app);230        (0, server_destroy_1.allowDestroy)(svr);231        // @ts-ignore232        return svr;233    }234    _port() {235        return this.server.address().port;236    }237    _listen(port, onError) {238        return new bluebird_1.default((resolve) => {239            const listener = () => {240                const address = this.server.address();241                this.isListening = true;242                debug('Server listening on ', address);243                this.server.removeListener('error', onError);244                return resolve(address.port);245            };246            return this.server.listen(port || 0, '127.0.0.1', listener);247        });248    }249    _onRequest(headers, automationRequest, options) {250        // @ts-ignore251        return this.request.sendPromise(headers, automationRequest, options);252    }253    _callRequestListeners(server, listeners, req, res) {254        return listeners.map((listener) => {255            return listener.call(server, req, res);256        });257    }258    _normalizeReqUrl(server) {259        // because socket.io removes all of our request260        // events, it forces the socket.io traffic to be261        // handled first.262        // however we need to basically do the same thing263        // it does and after we call into socket.io go264        // through and remove all request listeners265        // and change the req.url by slicing out the host266        // because the browser is in proxy mode267        const listeners = server.listeners('request').slice(0);268        server.removeAllListeners('request');269        server.on('request', (req, res) => {270            setProxiedUrl(req);271            this._callRequestListeners(server, listeners, req, res);272        });273    }274    _getRemoteState() {275        // {276        //   origin: "http://localhost:2020"277        //   fileServer:278        //   strategy: "file"279        //   domainName: "localhost"280        //   props: null281        // }282        // {283        //   origin: "https://foo.google.com"284        //   strategy: "http"285        //   domainName: "google.com"286        //   props: {287        //     port: 443288        //     tld: "com"289        //     domain: "google"290        //   }291        // }292        const props = lodash_1.default.extend({}, {293            auth: this._remoteAuth,294            props: this._remoteProps,295            origin: this._remoteOrigin,296            strategy: this._remoteStrategy,297            visiting: this._remoteVisitingUrl,298            domainName: this._remoteDomainName,299            fileServer: this._remoteFileServer,300        });301        debug('Getting remote state: %o', props);302        return props;303    }304    _onDomainSet(fullyQualifiedUrl, options = {}) {305        const l = (type, val) => {306            return debug('Setting', type, val);307        };308        this._remoteAuth = options.auth;309        l('remoteAuth', this._remoteAuth);310        // if this isn't a fully qualified url311        // or if this came to us as <root> in our tests312        // then we know to go back to our default domain313        // which is the localhost server314        if ((fullyQualifiedUrl === '<root>') || !fullyQualifiedRe.test(fullyQualifiedUrl)) {315            this._remoteOrigin = `http://${DEFAULT_DOMAIN_NAME}:${this._port()}`;316            this._remoteStrategy = 'file';317            this._remoteFileServer = `http://${DEFAULT_DOMAIN_NAME}:${(this._fileServer != null ? this._fileServer.port() : undefined)}`;318            this._remoteDomainName = DEFAULT_DOMAIN_NAME;319            this._remoteProps = null;320            l('remoteOrigin', this._remoteOrigin);321            l('remoteStrategy', this._remoteStrategy);322            l('remoteHostAndPort', this._remoteProps);323            l('remoteDocDomain', this._remoteDomainName);324            l('remoteFileServer', this._remoteFileServer);325        }326        else {327            this._remoteOrigin = (0, origin_1.default)(fullyQualifiedUrl);328            this._remoteStrategy = 'http';329            this._remoteFileServer = null;330            // set an object with port, tld, and domain properties331            // as the remoteHostAndPort332            this._remoteProps = network_1.cors.parseUrlIntoDomainTldPort(this._remoteOrigin);333            // @ts-ignore334            this._remoteDomainName = lodash_1.default.compact([this._remoteProps.domain, this._remoteProps.tld]).join('.');335            l('remoteOrigin', this._remoteOrigin);336            l('remoteHostAndPort', this._remoteProps);337            l('remoteDocDomain', this._remoteDomainName);338        }339        return this._getRemoteState();340    }341    proxyWebsockets(proxy, socketIoRoute, req, socket, head) {342        // bail if this is our own namespaced socket.io request343        if (req.url.startsWith(socketIoRoute)) {344            if (!this.socketAllowed.isRequestAllowed(req)) {345                socket.write('HTTP/1.1 400 Bad Request\r\n\r\nRequest not made via a Cypress-launched browser.');346                socket.end();347            }348            // we can return here either way, if the socket is still valid socket.io will hook it up349            return;350        }351        const host = req.headers.host;352        if (host) {353            // get the protocol using req.connection.encrypted354            // get the port & hostname from host header355            const fullUrl = `${req.connection.encrypted ? 'https' : 'http'}://${host}`;356            const { hostname, protocol } = url_1.default.parse(fullUrl);357            const { port } = network_1.cors.parseUrlIntoDomainTldPort(fullUrl);358            const onProxyErr = (err, req, res) => {359                return debug('Got ERROR proxying websocket connection', { err, port, protocol, hostname, req });360            };361            return proxy.ws(req, socket, head, {362                secure: false,363                target: {364                    host: hostname,365                    port,366                    protocol,367                },368                agent: network_1.agent,369            }, onProxyErr);370        }371        // we can't do anything with this socket372        // since we don't know how to proxy it!373        if (socket.writable) {374            return socket.end();375        }376    }377    reset() {378        var _a, _b;379        (_a = this._networkProxy) === null || _a === void 0 ? void 0 : _a.reset();380        const baseUrl = (_b = this._baseUrl) !== null && _b !== void 0 ? _b : '<root>';381        return this._onDomainSet(baseUrl);382    }383    _close() {384        // bail early we dont have a server or we're not385        // currently listening386        if (!this._server || !this.isListening) {387            return bluebird_1.default.resolve(true);388        }389        this.reset();390        logger_1.default.unsetSettings();391        evil_dns_1.default.clear();392        return this._server.destroyAsync()393            .then(() => {394            this.isListening = false;395        });396    }397    close() {398        var _a, _b, _c;399        return bluebird_1.default.all([400            this._close(),401            (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(),402            (_b = this._fileServer) === null || _b === void 0 ? void 0 : _b.close(),403            (_c = this._httpsProxy) === null || _c === void 0 ? void 0 : _c.close(),404        ])405            .then((res) => {406            this._middleware = null;407            return res;408        });409    }410    end() {411        return this._socket && this._socket.end();412    }413    changeToUrl(url) {414        return this._socket && this._socket.changeToUrl(url);415    }416    onRequest(fn) {417        this._middleware = fn;418    }419    onNextRequest(fn) {420        return this.onRequest((...args) => {421            fn.apply(this, args);422            this._middleware = null;423        });424    }425    onUpgrade(req, socket, head, socketIoRoute) {426        debug('Got UPGRADE request from %s', req.url);427        return this.proxyWebsockets(this.nodeProxy, socketIoRoute, req, socket, head);428    }429    callListeners(req, res) {430        const listeners = this.server.listeners('request').slice(0);431        return this._callRequestListeners(this.server, listeners, req, res);432    }433    onSniUpgrade(req, socket, head) {434        const upgrades = this.server.listeners('upgrade').slice(0);435        return upgrades.map((upgrade) => {436            return upgrade.call(this.server, req, socket, head);437        });438    }439    onConnect(req, socket, head) {440        debug('Got CONNECT request from %s', req.url);441        socket.once('upstream-connected', this.socketAllowed.add);442        return this.httpsProxy.connect(req, socket, head);443    }444    sendSpecList(specs, testingType) {445        return this.socket.sendSpecList(specs, testingType);446    }447}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.terminateAllWorkers = exports.createInitialWorkers = exports.DeferredSourceMapCache = exports.rewriteHtmlJsAsync = exports.rewriteJsAsync = exports.HtmlJsRewriter = void 0;4var html_1 = require("./html");5Object.defineProperty(exports, "HtmlJsRewriter", { enumerable: true, get: function () { return html_1.HtmlJsRewriter; } });6var async_rewriters_1 = require("./async-rewriters");7Object.defineProperty(exports, "rewriteJsAsync", { enumerable: true, get: function () { return async_rewriters_1.rewriteJsAsync; } });8Object.defineProperty(exports, "rewriteHtmlJsAsync", { enumerable: true, get: function () { return async_rewriters_1.rewriteHtmlJsAsync; } });9var deferred_source_map_cache_1 = require("./deferred-source-map-cache");10Object.defineProperty(exports, "DeferredSourceMapCache", { enumerable: true, get: function () { return deferred_source_map_cache_1.DeferredSourceMapCache; } });11var threads_1 = require("./threads");12Object.defineProperty(exports, "createInitialWorkers", { enumerable: true, get: function () { return threads_1.createInitialWorkers; } });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const worker = Cypress.cy.createInitialWorkers('worker.js')[0];2let response;3worker.postMessage('fetch');4worker.onmessage = function (e) {5  response = e.data;6};7self.onmessage = function (e) {8  if (e.data === 'fetch') {9      response.json().then((data) => {10        self.postMessage(data);11      })12    );13  }14};15cy.createWorker(workerOptions?: WorkerOptions): Worker16let response;17cy.createWorker().then((worker) => {18  worker.postMessage('fetch');19  worker.onmessage = function (e) {20    response = e.data;21  };22});23self.onmessage = function (e) {24  if (e.data === 'fetch') {25      response.json().then((data) => {26        self.postMessage(data);27      })28    );29  }30};31cy.createInitialWorkers(workerUrl: string, workerOptions?: WorkerOptions): Worker[]

Full Screen

Using AI Code Generation

copy

Full Screen

1const worker = Cypress.cy.createInitialWorkers('worker.js')[0];2let response;3worker.postMessage('fetch');4worker.onmessage = function (e) {5  response = e.data;6};7self.onmessage = function (e) {8  if (e.data === 'fetch') {9      response.json().then((data) => {10        self.postMessage(data);11      })12    );13  }14};15cy.createWorker(workerOptions?: WorkerOptions): Worker16let response;17cy.createWorker().then((worker) => {18  worker.postMessage('fetch');19  worker.onmessage = function (e) {20    response = e.data;21  };22});23self.onmessage = function (e) {24  if (e.data === 'fetch') {25      response.json().then((data) => {26        self.postMessage(data);27      })28    );29  }30};31cy.createInitialWorkers(workerUrl: string, workerOptions?: WorkerOptions): Worker[]32| `workerUrl`     |Workers(1)

Full Screen

Using AI Code Generation

copy

Full Screen

1const worker = Cypress.cy.createInitialWorkers('worker.js')[0];2let response;3worker.postMessage('fetch');4worker.onmessage = function (e) {5  response = e.data;6};7self.onmessage = function (e) {8  if (e.data === 'fetch') {9      response.json().then((data) => {10        self.postMessage(data);11      })12    );13  }14};15cy.createWorker(workerOptions?: WorkerOptions): Worker16let response;17cy.createWorker().then((worker) => {18  worker.postMessage('fetch');19  worker.onmessage = function (e) {20    response = e.data;21  };22});23self.onmessage = function (e) {24  if (e.data === 'fetch') {25      response.json().then((data) => {26        self.postMessage(data);27      })28    );29  }30};31cy.createInitialWorkers(workerUrl: string, workerOptions?: WorkerOptions): Worker[]

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful