Best JavaScript code snippet using testcafe
server.js
Source:server.js  
1var Path         = require('path'),2    Fs           = require('fs'),3    Express      = require('express'),4    EventEmitter = require('events').EventEmitter,5    Process      = require('child_process'),6    Url          = require('url'),7    uuid         = require('node-uuid'),8    http         = require('http');9//Const10var PORT                = 1335,11    CROSS_DOMAIN_PORT   = 1336,12    BASE_PATH           = __dirname,13    FIXTURES_PATH       = Path.join(BASE_PATH, '/fixtures'),14    SANDBOX_PATH        = Path.join(BASE_PATH, '/sandbox'),15    MARKUP_PATH         = Path.join(BASE_PATH, '/markup'),16    SANDBOX_MARKUP_PATH = Path.join(BASE_PATH, '/markup/sandbox'),17    VIEWS_PATH          = Path.join(BASE_PATH, '/views'),18    CUSTOM_SETUP_PATH   = Path.join(BASE_PATH, '/custom_setup.js'),19    COMPILED_PATH       = Path.join(BASE_PATH, '../../_compiled_'),20    TEST_PAGE_VIEW      = './test_page_template.ejs',21    SANDBOX_PAGE_VIEW   = './sandbox_page_template.ejs',22    DIR_LIST_VIEW       = './dir.ejs',23    TASK_REPORT_VIEW    = './task_report.ejs',24    TEST_SETUP_FILE     = Path.join(BASE_PATH, 'test_page_setup.js'),25    SANDBOX_SETUP_FILE  = Path.join(BASE_PATH, 'sandbox_page_setup.js');26//Globals27var appServer   = null,28    pageSetupJs = null;29var contentType = {30    '.js':   'application/javascript',31    '.css':  'text/css',32    '.html': 'text/html',33    '':      'text/html'34};35//Utils36function fileExists (path) {37    try {38        Fs.statSync(path);39        return true;40    } catch (x) {41        return false;42    }43}44function isDir (path) {45    return Fs.statSync(path).isDirectory();46}47function isHiddenFile (path) {48    path = Path.basename(path);49    return path[0] == '_' || path[0] == '.';50}51function isTestFile (path) {52    var isFixtureDirectory = path.indexOf(FIXTURES_PATH) > -1;53    path = Path.basename(path);54    return isFixtureDirectory && /\.js$/i.test(path);55}56function isSandboxTestFile (path) {57    var isSandboxDirectory = path.indexOf(SANDBOX_PATH) > -1;58    path = Path.basename(path);59    return isSandboxDirectory && /\.js$/i.test(path);60}61function getTests (path) {62    var tasks = [],63        i     = 0;64    var res = readDir(path);65    for (i = 0; i < res.files.length; i++) {66        tasks.push(Path.join(path, res.files[i]));67    }68    for (i = 0; i < res.dirs.length; i++) {69        tasks = tasks.concat(getTests(Path.join(path, res.dirs[i])));70    }71    return tasks;72}73function readDir (path) {74    var result = {75        dirs:  [],76        files: []77    };78    Fs.readdirSync(path).forEach(function (entry) {79        var subpath = Path.join(path, entry);80        if (isDir(subpath)) {81            result.dirs.push(entry);82        }83        if (isTestFile(subpath) || isSandboxTestFile(subpath)) {84            result.files.push(entry);85        }86    });87    result.dirs.sort();88    result.files.sort();89    return result;90}91function pathToUrl (path) {92    return path.substr(BASE_PATH.length).replace(/\\/g, '/');93}94function urlToPath (url) {95    return Path.join(BASE_PATH, url);96}97function getFileData (filename) {98    return Fs.readFileSync(filename).toString();99}100function getTestMarkUp (path) {101    var markUpPath = path.replace(FIXTURES_PATH, MARKUP_PATH).replace('.js', '.html');102    return fileExists(markUpPath) ?103           getFileData(markUpPath) :104           ''105}106function getSandboxMarkUp (path) {107    var markUpPath = path.replace(SANDBOX_PATH, SANDBOX_MARKUP_PATH).replace('.js', '.html');108    return fileExists(markUpPath) ?109           getFileData(markUpPath) :110           ''111}112function getCustomSetupJs () {113    return fileExists(CUSTOM_SETUP_PATH) ?114           getFileData(CUSTOM_SETUP_PATH) :115           ''116}117//Tasks118var tasks = {};119function createTask (path) {120    var tests = getTests(path),121        uid   = uuid.v4();122    var task = {123        uid:       uid,124        path:      path,125        tests:     tests,126        total:     tests.length,127        completed: 0,128        failed:    0,129        passed:    0,130        reports:   [],131        results:   []132    };133    tasks[uid] = task;134    return task;135}136function onTestComplete (res, testReport, taskUid, userAgent) {137    var task = tasks[taskUid];138    //NOTE: check task have already completed139    if (task.completed === task.total) {140        res.set('Location', pathToUrl(task.path));141        res.send(302);142        return;143    }144    task.results.push({145        name:   task.tests[task.completed],146        result: testReport147    });148    task.reports.push(testReport);149    task.completed++;150    if (testReport.errReport && testReport.errReport.report) {151        task.failed++;152    }153    else {154        task.passed++;155    }156    var nextTestUrl = task.completed === task.total ? null : pathToUrl(task.tests[task.completed]);157    //NOTE: This route is necessary for use of server.js as module. This route is taking tests report and send for further processing.158    if (!nextTestUrl) {159        appServer.emit('tests_complete', task, userAgent);160    }161    res.send(nextTestUrl || '/get-report');162}163function getReport (taskUid) {164    var task           = tasks[taskUid],165        preparedReport = {166            uid:       taskUid,167            path:      pathToUrl(task.path),168            total:     task.total,169            completed: task.completed,170            success:   task.passed,171            failed:    []172        };173    for (var i = 0; i < task.reports.length; i++) {174        var taskReport = task.reports[i];175        if (taskReport.errReport && taskReport.errReport.report) {176            for (var j = 0; j < taskReport.errReport.report.length; j++) {177                var report = taskReport.errReport.report[j];178                report.testPath = pathToUrl(task.tests[i]);179                preparedReport.failed.push(report);180            }181        }182    }183    return preparedReport;184}185function runTests (res, path) {186    var task = createTask(path);187    if (task.tests.length) {188        runTest(res, task.tests[0], task.uid);189    }190    else {191        res.set('Location', pathToUrl(path));192        res.send(302);193    }194}195function runTest (res, path, taskUid) {196    var data = {197        testPageSetup:       pageSetupJs,198        testMarkup:          getTestMarkUp(path),199        testFixture:         getFileData(path),200        customTestPageSetup: getCustomSetupJs(),201        taskUid:             taskUid202    };203    res.render(TEST_PAGE_VIEW, data);204}205function runSandbox (res, path, taskUid) {206    var data = {207        testPageSetup:       '',208        testMarkup:          getSandboxMarkUp(path),209        testFixture:         getFileData(path),210        customTestPageSetup: getFileData(SANDBOX_SETUP_FILE),211        taskUid:             taskUid212    };213    res.render(SANDBOX_PAGE_VIEW, data);214}215//NOTE: Url rewrite proxied requests (e.g. for iframes), so they will hit our server216function urlRewriteProxyRequest (req, res, next) {217    var proxiedUrlPartRegExp = /^\/\S+?\/(https?:)/;218    if (proxiedUrlPartRegExp.test(req.url)) {219        // NOTE: store original URL so we can sent it back for testing purposes (see GET xhr-test route).220        req.originalUrl = req.url;221        var url = req.url.replace(proxiedUrlPartRegExp, '$1');222        //NOTE: create host-relative URL223        var parsedUrl      = Url.parse(url);224        parsedUrl.host     = null;225        parsedUrl.hostname = null;226        parsedUrl.port     = null;227        parsedUrl.protocol = null;228        parsedUrl.slashes  = false;229        req.url            = Url.format(parsedUrl);230    }231    next();232}233var start = function (silent) {234    runCrossDomainServer();235    var app        = Express(),236        currentDir = FIXTURES_PATH;237    appServer = http.createServer(app);238    EventEmitter.call(appServer);239    pageSetupJs = getFileData(TEST_SETUP_FILE);240    app.set('views', VIEWS_PATH);241    app.use(urlRewriteProxyRequest);242    app.use(Express.bodyParser());243    app.use('/testcafe_client', Express.static(Path.join(COMPILED_PATH, './testcafe_client')));244    app.use('/hammerhead_client', Express.static(Path.join(COMPILED_PATH, './hammerhead_client')));245    //Prevent caching246    app.get('/*', function (req, res, next) {247        res.set('cache-control', 'no-cache, no-store, must-revalidate');248        next();249    });250    // Test purposes api251    app.get('/xhr-test/:delay', function (req, res) {252        var delay = req.params.delay || 0;253        setTimeout(function () {254            res.send(req.originalUrl);255        }, delay);256    });257    app.get('/xhr-large-response', function (req, res) {258        var data = new Array(1000);259        res.send(data);260    });261    app.post('/xhr-test/:delay', function (req, res) {262        var delay = req.params.delay || 0;263        setTimeout(function () {264            res.send('');265        }, delay);266    });267    app.get('/wrap-responseText-test/:isJSON', function (req, res) {268        var isJSON       = !!(req.params.isJSON === 'json'),269            responseText = isJSON ?270                           '{tag: "a", location: "location", attribute: {src: "example.com"}}' :271                           '<a href="example.com"><img src="img.png"></a>';272        res.send(responseText);273    });274    app.get('/iframe-test/:delay', function (req, res) {275        var delay = req.params.delay || 0;276        setTimeout(function () {277            res.send('');278        }, delay);279    });280    app.get('/get-script/:script', function (req, res) {281        var script = req.params.script || '';282        res.send(script);283    });284    app.post('/service-msg/:delay', function (req, res) {285        var delay = req.params.delay || 0;286        setTimeout(function () {287            res.send(delay);288        }, delay);289    });290    // Initialization291    app.all('/run-next-test', function (req, res) {292        onTestComplete(res, req.body.report, req.body.taskUid, req.headers['user-agent']);293    });294    app.all('/run-dir', function (req, res) {295        runTests(res, urlToPath(req.query.dir));296    });297    app.all('/get-report', function (req, res) {298        var taskUid = req.query.taskUid;299        res.render(TASK_REPORT_VIEW, getReport(taskUid));300    });301    app.all('/*', function (req, res) {302        var page    = req.params[0],303            path    = Path.join(BASE_PATH, page),304            taskUid = req.query.taskUid;305        path = path.replace(/[\\\/]+$/, '');306        res.header('Cache-Control', 'no-cache');307        if (!fileExists(path)) {308            res.send(404);309            return;310        }311        if (!page) {312            res.set('Location', '/fixtures');313            res.send(302);314        }315        else if (isDir(path)) {316            var data = readDir(path);317            data.currentDir = currentDir = Path.basename(path);318            data.currentUrl = pathToUrl(path);319            data.fixtures   = /^\/fixtures(\/|$)/i.test(data.currentUrl);320            res.render(DIR_LIST_VIEW, data);321        }322        else {323            if (isTestFile(path)) {324                runTest(res, path, taskUid);325            }326            else if (isSandboxTestFile(path)) {327                runSandbox(res, path, taskUid);328            }329            else {330                res.set('Content-Type', contentType[Path.extname(path)]);331                res.send(Fs.readFileSync(path, 'utf8'));332            }333        }334    });335    appServer.listen(PORT);336    console.log('Server listens on port ' + PORT);337    if (!silent)338        Process.exec('start http://localhost:' + PORT);339    return 'http://localhost:' + PORT;340};341function runCrossDomainServer () {342    var app = Express();343    appServer = http.createServer(app);344    app.use(urlRewriteProxyRequest);345    app.use('/testcafe_client', Express.static(Path.join(COMPILED_PATH, './testcafe_client')));346    app.use('/hammerhead_client', Express.static(Path.join(COMPILED_PATH, './hammerhead_client')));347    //Prevent caching348    app.get('/*', function (req, res, next) {349        res.set('cache-control', 'no-cache, no-store, must-revalidate');350        next();351    });352    app.get('/xhr-test/:delay', function (req, res) {353        var delay = req.params.delay || 0;354        setTimeout(function () {355            res.send(req.url);356        }, delay);357    });358    app.get('/*', function (req, res) {359        var path = Path.join(BASE_PATH, 'data/cross_domain', req.path);360        path = path.replace(/[\\\/]+$/, '');361        res.header('Cache-Control', 'no-cache');362        if (!fileExists(path)) {363            res.send(404);364            return;365        }366        res.set('Content-Type', 'text/html');367        res.send(Fs.readFileSync(path, 'utf8'));368    });369    appServer.listen(CROSS_DOMAIN_PORT);370}...config-qunit-server-app.js
Source:config-qunit-server-app.js  
1var url  = require('url');2var fs   = require('fs');3var path = require('path');4//The following code is copied from testcafe-hammerhead5//NOTE: Url rewrite proxied requests (e.g. for iframes), so they will hit our server6function urlRewriteProxyRequest (req, res, next) {7    var proxiedUrlPartRegExp = /^\/\S+?\/(https?:)/;8    if (proxiedUrlPartRegExp.test(req.url)) {9        // NOTE: store original URL so we can sent it back for testing purposes (see GET xhr-test route).10        req.originalUrl = req.url;11        var reqUrl = req.url.replace(proxiedUrlPartRegExp, '$1');12        //NOTE: create host-relative URL13        var parsedUrl = url.parse(reqUrl);14        parsedUrl.host     = null;15        parsedUrl.hostname = null;16        parsedUrl.port     = null;17        parsedUrl.protocol = null;18        parsedUrl.slashes  = false;19        req.url            = url.format(parsedUrl);20    }21    next();22}23module.exports = function (app) {24    app.use(urlRewriteProxyRequest);25    app.get('/wrap-responseText-test/:isJSON', function (req, res) {26        var isJSON       = req.params.isJSON === 'json';27        var responseText = isJSON ?28                           '{tag: "a", location: "location", attribute: {src: "example.com"}}' :29                           '<a href="example.com"><img src="img.png"></a>';30        res.send(responseText);31    });32    app.all('/xhr-test/:delay', function (req, res) {33        var delay = req.params.delay || 0;34        setTimeout(function () {35            res.send(req.originalUrl || req.url);36        }, delay);37    });38    app.get('/testcafe-ui-sprite.png', function (req, res) {39        fs.readFile(path.join(__dirname, '../../lib/client/ui/sprite.png'), function (err, image) {40            res.set('Content-Type', 'image/png');41            res.send(image);42        });43    });...Using AI Code Generation
1import { RequestHook } from 'testcafe';2class MyRequestHook extends RequestHook {3    constructor (requestFilterRules, responseEventConfigureOpts) {4        super(requestFilterRules, responseEventConfigureOpts);5    }6    async onRequest (event) {7        const request = event._requestInfo;8        await event._requestFilterRules.urlRewriteProxyRequest(newUrl);9    }10    async onResponse (event) {11    }12}13import { RequestHook } from 'testcafe';14class MyRequestHook extends RequestHook {15    constructor (requestFilterRules, responseEventConfigureOpts) {16        super(requestFilterRules, responseEventConfigureOpts);17    }18    async onRequest (event) {19    }20    async onResponse (event) {21        const response = event._responseInfo;22        const newBody = 'Hello World';23        await event._requestFilterRules.urlRewriteProxyResponse(newBody);24    }25}26import { RequestHook } from 'testcafe';27class MyRequestHook extends RequestHook {28    constructor (requestFilterRules, responseEventConfigureOpts) {29        super(requestFilterRules, responseEventConfigureOpts);30    }31    async onRequest (event) {32        await event._requestFilterRules.disableProxy();33    }34    async onResponse (event) {35    }36}37import { RequestHook } from 'testcafe';38class MyRequestHook extends RequestHook {39    constructor (requestFilterRules, responseEventUsing AI Code Generation
1import { RequestHook } from 'testcafe';2export default class MyHook extends RequestHook {3    constructor(requestFilterRules, responseEventConfigureOpts) {4        super(requestFilterRules, responseEventConfigureOpts);5    }6    async onRequest(event) {7    }8}9import MyHook from './test.js';10test('My test', async t => {11        .addRequestHooks(new MyHook())12});13import { RequestHook } from 'testcafe';14export default class MyHook extends RequestHook {15    constructor(requestFilterRules, responseEventConfigureOpts) {16        super(requestFilterRules, responseEventConfigureOpts);17    }18    async onConfigureResponse(event) {19        event.headers['x-added-header'] = 'added-header-value';20    }21}22import { RequestHook } from 'testcafe';23export default class MyHook extends RequestHook {24    constructor(requestFilterRules, responseEventUsing AI Code Generation
1import { RequestHook } from 'testcafe';2import { urlRewriteProxyRequest } from 'testcafe-hammerhead';3class MyRequestHook extends RequestHook {4    constructor (requestFilterRules, responseEventConfigureOpts) {5        super(requestFilterRules, responseEventConfigureOpts);6    }7    async onRequest (event) {8        const { request } = event;9    }10    async onResponse (event) {11    }12}13export default MyRequestHook;14import { RequestHook } from 'testcafe';15import { urlRewriteProxyResponse } from 'testcafe-hammerhead';16class MyRequestHook extends RequestHook {17    constructor (requestFilterRules, responseEventConfigureOpts) {18        super(requestFilterRules, responseEventConfigureOpts);19    }20    async onRequest (event) {21    }22    async onResponse (event) {23        const { response } = event;24    }25}26export default MyRequestHook;27import { RequestHook } from 'testcafe';28import { getProxyUrl } from 'testcafe-hammerhead';29class MyRequestHook extends RequestHook {30    constructor (requestFilterRules, responseEventConfigureOpts) {31        super(requestFilterRules, responseEventConfigureOpts);32    }33    async onRequest (event) {34        const { request } = event;35        const proxyUrl = getProxyUrl(request.url);36    }37    async onResponse (event) {38    }39}40export default MyRequestHook;41import { RequestHook } from 'testcafe';42import { getAuthCredentials } from 'testcaUsing AI Code Generation
1import { RequestHook } from 'testcafe';2import { urlRewriteProxyRequest } from 'testcafe-hammerhead';3class MyHook extends RequestHook {4    constructor (requestFilterRules, responseEventConfigureOpts) {5        super(requestFilterRules, responseEventConfigureOpts);6    }7    async onRequest (event) {8    }9    async onResponse (event) {10    }11}12export default MyHook;Using AI Code Generation
1import { RequestHook } from 'testcafe';2class MyRequestHook extends RequestHook {3    constructor (requestFilterRules, responseEventConfigureOpts) {4        super(requestFilterRules, responseEventConfigureOpts);5    }6    async onRequest (event) {7        }8    }9    async onResponse (event) {10    }11}12export default new MyRequestHook();Using AI Code Generation
1import { RequestMock } from 'testcafe';2const mock = RequestMock()3    .respond(null, 200, { 'access-control-allow-origin': '*' })4    .respond(null, 200, { 'access-control-allow-origin': '*' })5    .respond(null, 200, { 'access-control-allow-origin': '*' })6    .respond(null, 200, { 'access-control-allow-origin': '*' })7    .respond(null, 200, { 'access-control-allow-origin': '*' })8    .respond(null, 200, { 'access-control-allow-origin': '*' })9    .respond(null, 200, { 'access-control-allow-origin': '*' })10    .respond(null, 200, { 'access-control-allow-origin': '*' })11    .respond(null, 200, { 'access-control-allow-origin': '*' })12    .respond(null, 200, { 'access-control-allow-origin': '*' })13    .respond(null, 200, { 'access-control-allow-origin': '*' })14    .respond(null, 200, { 'access-control-allow-origin': '*' })15    .respond(null, 200, { 'access-control-allow-origin': '*' })16    .respond(null, 200, { 'access-control-allow-origin': '*' })Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
