Best JavaScript code snippet using testcafe
loaderTest.js
Source:loaderTest.js
...74 var modName = "/getscript/js/bespin/nonModule.js";75 76 lq[modName] = {resolver: this.resolver};77 78 bespin.plugins.loader.moduleLoaded(modName,79 function(require, exports) {80 loadCheck.didLoad = true;81 82 exports.secretValue = 27;83 84 return exports;85 });86 test.isTrue(loadCheck.didLoad);87 88 test.isUndefined(lq[modName], "Module should be gone from the queue");89 90 test.isNotUndefined(bespin.plugins.loader.modules[modName],91 "Was module object saved?");92 93 var nonModule = bespin.plugins.loader.modules[modName];94 test.isEqual(27, nonModule.secretValue);95 },96 97 testModuleWithSingleDep: function(test) {98 var lq = bespin.plugins.loader.loadQueue;99 100 loadCheck = {didLoad: false, otherDidLoad: false};101 var modName = "/getscript/js/bespin/nonModule.js";102 var depModName = "/getscript/js/bespin/depModule.js";103 104 bespin.plugins.loader.loadScript("bespin/nonModule",105 {resolver: this.resolver});106 107 bespin.plugins.loader.moduleLoaded(modName,108 function(require, exports) {109 var othermod = require("bespin/depModule");110 111 loadCheck.didLoad = true;112 113 exports.secretValue = othermod.secretValue;114 115 return exports;116 });117 118 test.isFalse(loadCheck.didLoad);119 120 test.isNotUndefined(lq[modName], "main module should be in the queue");121 test.isNotUndefined(lq[depModName], 122 "dependent module should be in queue");123 test.isNotUndefined(lq[depModName].resolver);124 125 bespin.plugins.loader.moduleLoaded(depModName,126 function(require, exports) {127 loadCheck.otherDidLoad = true;128 129 exports.secretValue = 192;130 131 return exports;132 });133 134 test.isTrue(loadCheck.didLoad, "Main module should load");135 test.isTrue(loadCheck.otherDidLoad, "Module it depended on should load");136 137 console.dir(bespin.plugins.loader.modules);138 var mod = bespin.plugins.loader.modules[modName];139 test.isNotUndefined(mod, "The main module should be requireable");140 test.isEqual(192, mod.secretValue, "secret value should have been set");141 test.isEqual(modName, mod._name);142 143 var expectedDependencies = {};144 expectedDependencies[depModName] = true;145 test.isEqual(mod._depends_on, expectedDependencies);146 147 var depMod = bespin.plugins.loader.modules[depModName];148 test.isEqual(depModName, depMod._name);149 var expectedDependedOnBy = {};150 expectedDependedOnBy[modName] = true;151 test.isEqual(depMod._depended_on_by, expectedDependedOnBy);152 },153 154 testModuleLoadOrderShouldNotMatter: function(test) {155 var loader = bespin.plugins.loader;156 var lq = loader.loadQueue;157 var loadCheck = {};158 loader.loadScript("A", {159 resolver: this.resolver160 });161 162 loader.moduleLoaded("/getscript/js/A.js",163 function(require, exports) {164 loadCheck.A = true;165 var B = require("B");166 var C = require("C");167 168 return exports;169 });170 171 test.isUndefined(loadCheck.A, "A should not have been loaded yet");172 test.isNotUndefined(lq["/getscript/js/B.js"], "B should be queued up");173 test.isNotUndefined(lq["/getscript/js/C.js"], "C should be queued up");174 175 loader.moduleLoaded("/getscript/js/B.js",176 function(require, exports) {177 loadCheck.B = true;178 var D = require("D");179 180 return exports;181 });182 183 test.isUndefined(loadCheck.A, "A should not have been loaded");184 test.isUndefined(loadCheck.B, "B should not have been loaded");185 186 // D comes in out of order187 loader.moduleLoaded("/getscript/js/D.js",188 function(require, exports) {189 loadCheck.D = true;190 return exports;191 });192 193 test.isTrue(loadCheck.D, "D should *now* have been loaded");194 test.isTrue(loadCheck.B, "B should *now* have been loaded");195 test.isUndefined(loadCheck.A, "A should not have been loaded");196 197 loader.moduleLoaded("/getscript/js/C.js",198 function(require, exports) {199 loadCheck.C = true;200 201 var D = require("D");202 203 return exports;204 });205 206 test.isTrue(loadCheck.C, "C should *now* have been loaded");207 test.isTrue(loadCheck.A, "A should *now* have been loaded");208 },209 210 testDependenciesAreForceReloadedToo: function(test) {211 var loader = bespin.plugins.loader;212 var lq = loader.loadQueue;213 var loadCheck = {};214 loader.loadScript("A", {215 resolver: this.resolver216 });217 218 var Afactory = function(require, exports) {219 loadCheck.A = true;220 var B = require("B");221 222 return exports;223 };224 225 loader.moduleLoaded("/getscript/js/A.js",226 Afactory);227 228 test.isUndefined(loadCheck.A, "A should not have been loaded yet");229 test.isNotUndefined(lq["/getscript/js/B.js"], "B should be queued up");230 231 var Bfactory = function(require, exports) {232 loadCheck.B = true;233 234 return exports;235 };236 237 loader.moduleLoaded("/getscript/js/B.js",238 Bfactory);239 240 test.isNotUndefined(loadCheck.A, "A should be loaded");241 test.isNotUndefined(loadCheck.B, "B should be loaded");242 243 delete loadCheck.A;244 delete loadCheck.B;245 246 loader.loadScript("A", {247 resolver: this.resolver,248 force: true249 });250 251 loader.moduleLoaded("/getscript/js/A.js",252 Afactory);253 254 test.isUndefined(loadCheck.A, "A should not have been reloaded yet");255 test.isNotUndefined(lq["/getscript/js/B.js"], "B should be queued up");256 }...
app.js
Source:app.js
1'use strict';2const path = require('path');3const fileUpload = require('express-fileupload');4const express = require('express');5const app = express().set('express', express);6const cookieParser = require('cookie-parser');7const bodyParser = require('body-parser');8const fs = require('fs');9const winston = require('winston');10((async function init() { 11 try {12 const config = require(path.join(__dirname, 'config.js'));13 if (!config.log) {14 config.log = {};15 }16 const log = winston.createLogger({17 level: config.log.logLevel,18 format: winston.format.printf(info => {19 return new Date().toISOString() + ` [${info.level}] ${info.message}`;20 }),21 transports: [22 new winston.transports.File({23 dirname: config.log.dirname || path.join(__dirname, '..', 'logs'),24 filename: config.log.filename || 'main.log',25 maxsize: config.log.maxsize || 1048576,26 maxFiles: config.log.maxFiles || 10,27 tailable: config.log.tailable || true,28 timestamp: config.log.timestamp || false,29 showLevel: config.log.showLevel || false,30 meta: config.log.meta || false,31 json: config.log.json || false32 })33 ]34 });35 if (!config.production) {36 log.add(new winston.transports.Console({ colorize: true }));37 }38 app.set('log', log);39 log.info('Starting Zoia version ' + config.version);40 app.set('trust proxy', config.trustProxy);41 app.disable('x-powered-by');42 // Init database43 const db = new(require(path.join(__dirname, 'database.js')))(app, config.mongo, config.session);44 await db.connect();45 app.set('db', db.get());46 app.set('bruteforceStore', db.bruteforceStore);47 // Init parsers and other stuff48 app.use(bodyParser.json(), bodyParser.urlencoded({ extended: true, limit: config.maxUploadSizeMB + 'mb' }), cookieParser(), fileUpload(), express.static(path.join(__dirname, '..', 'static')));49 // Load preroutes50 const preroutes = new(require(path.join(__dirname, 'preroutes.js')))(app);51 for (let key of Object.keys(preroutes)) {52 app.use(preroutes[key]);53 }54 // Load modules55 const modules = fs.readdirSync(path.join(__dirname, '..', 'modules'));56 app.set('modules', modules);57 let templateFilters = {};58 let backendModules = [];59 log.info('Loading ' + modules.length + ' module(s)...');60 for (let m in modules) {61 const moduleLoaded = require(path.join(__dirname, '..', 'modules', modules[m], 'module'))(app);62 if (moduleLoaded) {63 if (moduleLoaded.frontend) {64 if (moduleLoaded.frontend.routes) {65 app.use(moduleLoaded.frontend.prefix, moduleLoaded.frontend.routes);66 if (config.i18n.detect.url) {67 for (let i in config.i18n.locales) {68 app.use('/' + config.i18n.locales[i] + moduleLoaded.frontend.prefix, moduleLoaded.frontend.routes);69 }70 }71 }72 if (moduleLoaded.frontend.filters) {73 for (let f in moduleLoaded.frontend.filters) {74 templateFilters[f] = moduleLoaded.frontend.filters[f];75 }76 }77 }78 if (moduleLoaded.backend && moduleLoaded.backend.routes) {79 if (moduleLoaded.backend.info) {80 backendModules.push(moduleLoaded.backend.info);81 }82 app.use(config.core.prefix.admin + moduleLoaded.backend.prefix, moduleLoaded.backend.routes);83 if (config.i18n.detect.url) {84 for (let i in config.i18n.locales) {85 app.use('/' + config.i18n.locales[i] + config.core.prefix.admin + moduleLoaded.backend.prefix, moduleLoaded.backend.routes);86 }87 }88 }89 if (moduleLoaded.api && moduleLoaded.api.routes) {90 app.use('/api' + moduleLoaded.api.prefix, moduleLoaded.api.routes);91 }92 }93 }94 app.set('backendModules', backendModules);95 app.set('templateFilters', templateFilters);96 const errors = new(require(path.join(__dirname, 'errors.js')))(app);97 app.use(errors.notFound, errors.errorHandler);98 app.emit('zoiaStarted');99 log.info('Starting...');100 } catch (e) {101 // That's error102 console.log(e);103 process.exit(1);104 }105})());...
SettingsRenderer.js
Source:SettingsRenderer.js
1/**2 * Settings Renderer component.3 *4 * Site Kit by Google, Copyright 2021 Google LLC5 *6 * Licensed under the Apache License, Version 2.0 (the "License");7 * you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * https://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18/**19 * WordPress dependencies20 */21import { useEffect, useState } from '@wordpress/element';22import { useParams } from 'react-router-dom';23/**24 * Internal dependencies25 */26import Data from 'googlesitekit-data';27import { CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';28const { useSelect, useDispatch } = Data;29export default function SettingsRenderer( { slug } ) {30 const { action, moduleSlug } = useParams();31 const isEditing = action === 'edit';32 const isOpen = moduleSlug === slug;33 const [ initiallyConnected, setInitiallyConnected ] = useState();34 const isDoingSubmitChanges = useSelect( ( select ) =>35 select( CORE_MODULES ).isDoingSubmitChanges( slug )36 );37 const {38 SettingsEditComponent,39 SettingsViewComponent,40 SettingsSetupIncompleteComponent,41 moduleLoaded,42 connected,43 } = useSelect( ( select ) => {44 const module = select( CORE_MODULES ).getModule( slug );45 return {46 ...module,47 moduleLoaded: !! module,48 };49 } );50 // Store the initial connected state once the module is loaded.51 useEffect( () => {52 if ( moduleLoaded && initiallyConnected === undefined ) {53 setInitiallyConnected( connected );54 }55 }, [ moduleLoaded, initiallyConnected, connected ] );56 // Rollback any temporary selections to saved values if settings have changed and no longer editing.57 const { rollbackChanges } = useDispatch( CORE_MODULES );58 useEffect( () => {59 if ( ! isDoingSubmitChanges && ! isEditing ) {60 rollbackChanges( slug );61 }62 }, [ slug, rollbackChanges, isDoingSubmitChanges, isEditing ] );63 if ( ! isOpen || ! moduleLoaded ) {64 return null;65 } else if ( isOpen && initiallyConnected === false ) {66 return <SettingsSetupIncompleteComponent slug={ slug } />;67 }68 if ( isEditing && SettingsEditComponent ) {69 return <SettingsEditComponent />;70 } else if ( SettingsViewComponent ) {71 return <SettingsViewComponent />;72 }73 return null;...
miradorInit.js
Source:miradorInit.js
1const bdr = "http://purl.bdrc.io/resource/"2let iiifpres = "//iiifpres.bdrc.io"3let miradorConfig, miradorSetUI4async function init() {5 const urlParams = new URLSearchParams(window.location.search);6 const work = urlParams.get('work') || "bdr:W22084";7 if(urlParams.get('iiifpres')) iiifpres = "//" + urlParams.get('iiifpres') ;8 let data = [9 { "collectionUri" :iiifpres+"/2.1.1/collection/wio:"+work, location:"" }10 ]11 let lg = urlParams.get('lang') || "bo,zh-hans";12 lg = lg.split(",")13 let config = miradorConfig(data,null,null,null,lg,null,work);14 window.Mirador( config )15 miradorSetUI();16}17let waiter = setInterval( async ()=>{18 console.log("waiting")19 const urlParams = new URLSearchParams(window.location.search);20 let origin = urlParams.get('origin') ;21 if(!origin)22 {23 window.$("#viewer").html("<div style='margin:20px'><h2>Embedded iframe must set <i>origin</i> parameter.<br/>See <a target='_blank' href='https://github.com/buda-base/public-digital-library/blob/master/BDRC_Embedded_Reader.md'>documentation</a> for further information.</h2></div>")24 clearInterval(waiter)25 }26 else if(_ && window.moduleLoaded && window.moduleLoaded.JsEWTS && window.moduleLoaded.Sanscript && window.moduleLoaded.pinyin4js && window.moduleLoaded.hanziConv) {27 clearInterval(waiter);28 miradorConfig = window.miradorConfig29 miradorSetUI = window.miradorSetUI30 window.closeViewer = () => { parent.window.postMessage("close", "*"); }31 //init();32 const work = urlParams.get('work') || "bdr:W22084";33 let lg = urlParams.get('lang') || "bo,zh-hans";34 let uilg = urlParams.get('uilang') || "bo";35 lg = lg.split(",")36 window.miradorInitView(work,lg,null,uilg);37 }...
webserver-route-loader.js
Source:webserver-route-loader.js
1const fs = require('fs');2const path = require('path');3const express = require('express');4const fsUtils = require('../utils/fs');5module.exports = function (webserver, baseDir = __dirname, routePath = null) {6 const logger = require('../logging')('abbott-framework:webserver-route-loader');7 let server = webserver.server;8 9 var parentRoute = server;10 if (routePath) {11 parentRoute = express.Router();12 server.use(routePath, parentRoute);13 }14 let moduleLoaded = null;15 try {16 moduleLoaded = require(baseDir);17 } catch(err) {}18 if (moduleLoaded) {19 loadSubRoute(moduleLoaded, parentRoute, routePath);20 }21 let routeDirectories = null;22 try {23 let baseDirStats = fs.lstatSync(baseDir);24 if (baseDirStats.isDirectory()) {25 routeDirectories = fsUtils.getDirectories(baseDir);26 }27 } catch (err) {}28 29 if (routeDirectories) {30 routeDirectories.forEach((routeApiItem) => {31 logger.info(`directories: (${baseDir} / ${routeApiItem})`);32 33 loadSubRoute(require(path.join(baseDir, routeApiItem)), parentRoute, routePath, routeApiItem);34 });35 }36 function loadSubRoute(apiSubRoute, parentRoute, routePath, routeApiItem) {37 if (apiSubRoute) {38 let subPath = routePath || '/';39 let apiRoutePath = path.join(subPath, routeApiItem || '');40 let router = express.Router();41 apiSubRoute(webserver, router);42 parentRoute.use(apiRoutePath, router);43 logger.info(`subroute loaded (${apiRoutePath})!`);44 }45 }46 47 return parentRoute;...
index.js
Source:index.js
1import React from 'react';2import ReactWasmBridge from 'react-wasm-bridge';3let mdModule;4let modulePromise;5export default class MarkdownWasm extends React.PureComponent {6 constructor() {7 super();8 if (!mdModule) {9 if (!modulePromise) {10 modulePromise = import('./react_markdown_wasm');11 }12 modulePromise.then(m => {13 mdModule = m;14 this.setState({ moduleLoaded: true });15 }).catch(e => {16 console.error(e);17 });18 this.state = {19 moduleLoaded: false20 };21 } else {22 this.state = {23 moduleLoaded: true24 }25 }26 }27 render() {28 const { children } = this.props;29 const { moduleLoaded } = this.state;30 if (!moduleLoaded) {31 return null;32 }33 return <ReactWasmBridge module={ mdModule } message={ children } method="dom" />;34 }...
ModuleManager.js
Source:ModuleManager.js
1'use strict';2const fs = require('fs');3const path = require('path');4const Util = require('../util/Util');5class ModuleManager {6 constructor() {7 throw new Error(`The ${this.constructor.name} class may not be instantiated.`);8 }9 static load(client, type, name) {10 let moduleLoaded = {};11 type += 's';12 if (client.noobOptions[type] && fs.existsSync(Util.getCurrentPath(path.join(client.noobOptions[type], name + ".js")))) {13 moduleLoaded = require(Util.getCurrentPath(path.join(client.noobOptions[type], name)));14 } else if (fs.existsSync(path.join(__dirname, '/../modules/', type, name + ".js"))) {15 moduleLoaded = require(path.join('../modules/', type, name));16 }17 18 return moduleLoaded;19 }20}...
factory.js
Source:factory.js
1define(['container', 'section', 'item'], function (Container, Section, Item) {2 var Factory = (function () {3 var moduleLoaded;4 function Factory(module, text) {5 switch (module) {6 case 'container' :7 moduleLoaded = new Container(text);8 moduleLoaded.addToDom(document.body);9 break;10 case 'section':11 moduleLoaded = new Section(text);12 break;13 case 'item':14 moduleLoaded = new Item(text);15 break;16 default:17 throw new Error("Undefined module provided.");18 }19 }20 return Factory;21 }());22 return Factory;...
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7module.exports = {8 async moduleLoaded() {9 console.log('module loaded');10 },11 async moduleUnloaded() {12 console.log('module unloaded');13 },14 async testRunFinished() {15 console.log('test run finished');16 },17 async testRunStarted() {18 console.log('test run started');19 }20};21import { Selector } from 'testcafe';22test('My first test', async t => {23 .typeText('#developer-name', 'John Smith')24 .click('#submit-button')25 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');26});27module.exports = {28 async moduleLoaded() {29 console.log('module loaded');30 },31 async moduleUnloaded() {32 console.log('module unloaded');33 },34 async testRunFinished() {35 console.log('test run finished');36 },37 async testRunStarted() {38 console.log('test run started');39 }40};41import { Selector } from 'testcafe';42test('My first test', async t => {43 .typeText('#developer-name', 'John Smith')44 .click('#submit-button')45 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');46});47module.exports = {48 async moduleLoaded() {49 console.log('module loaded');50 },51 async moduleUnloaded() {52 console.log('module unloaded');53 },54 async testRunFinished() {55 console.log('
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7});8import { Selector } from 'testcafe';9test('My first test', async t => {10 .typeText('#developer-name', 'John Smith')11 .click('#submit-button');12 const articleHeader = await Selector('.result-content').find('h1');13 let headerText = await articleHeader.innerText;14});15import { Selector } from 'testcafe';16test('My first test', async t => {17 .typeText('#developer-name', 'John Smith')18 .click('#submit-button');19 const articleHeader = await Selector('.result-content').find('h1');20 let headerText = await articleHeader.innerText;21});22import { Selector } from 'testcafe';23test('My first test', async t => {24 .typeText('#developer-name', 'John Smith')25 .click('#submit-button');26 const articleHeader = await Selector('.result-content').find('h1');27 let headerText = await articleHeader.innerText;28});29import { Selector } from 'testcafe';
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7 await t.expect(headerText).eql('Thank you, John Smith!');8});9import { Selector } from 'testcafe';10test('My first test', async t => {11 .typeText('#developer-name', 'John Smith')12 .click('#submit-button');13 const articleHeader = await Selector('.result-content').find('h1');14 let headerText = await articleHeader.innerText;15 await t.expect(headerText).eql('Thank you, John Smith!');16});17import { Selector } from 'testcafe';18test('My first test', async t => {19 .typeText('#developer-name', 'John Smith')20 .click('#submit-button');21 const articleHeader = await Selector('.result-content').find('h1');22 let headerText = await articleHeader.innerText;23 await t.expect(headerText).eql('Thank you, John Smith!');24});25import { Selector } from 'testcafe';26test('My first test', async t => {27 .typeText('#developer-name', 'John Smith')28 .click('#submit-button');29 const articleHeader = await Selector('.result-content').find('h1');
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const moduleLoaded = ClientFunction(() => {3 return new Promise(resolve => {4 window.moduleLoaded = resolve;5 });6});7test('test', async t => {8 .click('#gb_70')9 .typeText('#identifierId', '
Using AI Code Generation
1 .beforeEach(async t => {2 .wait(2000)3 .debug();4 });5test('My Test', async t => {6 .wait(5000)7 .debug();8});
Using AI Code Generation
1 .beforeEach(async t => {2 .wait(5000)3 .maximizeWindow()4 .click('#test-button')5 .wait(5000)6 })7 .afterEach(async t => {8 .wait(5000)9 });10test('TestCafe', async t => {11 .wait(5000)12 .expect(Selector('#test').innerText).eql('TestCafe')13 .wait(5000)14});15 .beforeEach(async t => {16 .wait(5000)17 .maximizeWindow()18 .click('#test-button')19 .wait(5000)20 })21 .afterEach(async t => {22 .wait(5000)23 });24test('TestCafe2', async t => {25 .wait(5000)26 .expect(Selector('#test').innerText).eql('TestCafe')27 .wait(5000)28});29 .beforeEach(async t => {30 .wait(5000)31 .maximizeWindow()32 .click('#test-button')33 .wait(5000)34 })35 .afterEach(async t => {36 .wait(5000)37 });38test('TestCafe3', async t => {39 .wait(5000)40 .expect(Selector('#test').innerText).eql('TestCafe')41 .wait(5000)42});43 .beforeEach(async t => {44 .wait(5000)45 .maximizeWindow()46 .click('#test-button')47 .wait(5000)
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!!