Best JavaScript code snippet using jest
consoleCli.js
Source:consoleCli.js
...234 console.log(`${cmd}`);235 walletMgr.shutdown();236 return false;237 }238 await data.execFunction(cmd, words, wallet, walletMgr);239 return true;240 } else {241 console.log(`Illegal command: ${cmd}`);242 helpFunc();243 }244 return true;245};246// call node wallet-console.js createwallet -n regtest -c ./docker/bitcoin.conf -u User -i 1 -s '0e09fbdd00e575b654d480ae979f24da45ef4dee645c7dc2e3b30b2e093d38dda0202357754cc856f8920b8e31dd02e9d34f6a2b20dc825c6ba90f90009085e1' -d "./testdata/"247const help = function() {248 console.log(' Usage: node wallet-console createwallet -n <network> -n <network> -c <configFile> -i <userIndex> -s <seed> [-u <userPrefix>] [-d <dataDirPath>] [-t <targetName>]');249 console.log(' node wallet-console help');250 console.log('');251 console.log(' option:');252 console.log(' -n network name. (mainnet, testnet, regtest, liquidv1, elementsregtest)');...
docker-tasks.js
Source:docker-tasks.js
1const shelljs = require("shelljs");2const dockerTasks = (execFunction = shelljs, props, args) => {3 const printHelpText = () => {4 execFunction.echo("docker-tasks");5 execFunction.echo("");6 execFunction.echo("Usage:");7 execFunction.echo("");8 execFunction.echo(" yarn docker-tasks help Prints this help text.");9 execFunction.echo(" yarn docker-tasks genconfig Generates a configuration file for you to edit with your project details.");10 execFunction.echo(" yarn docker-tasks build [-p] Builds the image. Use -p to prune before building.");11 execFunction.echo(" yarn docker-tasks run Runs the container.");12 execFunction.echo(" yarn docker-tasks debug Runs the container as above but overrides the entry point with `bash` so you can take a look inside. (Note: Because of how shelljs works the debug command cannot be run directly. Instead, this will print out a command for you to run yourself.)");13 execFunction.echo(" yarn docker-tasks clear Stops and removes the container.");14 execFunction.echo(" yarn docker-tasks prune Removes unused data.");15 execFunction.echo(" yarn docker-tasks release <version> Tags '<imageName>:latest' as '<imageName>:<version>', then runs \"docker push <imageName>:latest\" followed by \"docker push <imageName>:<version>\".");16 execFunction.echo("");17 execFunction.echo("Use -n/--dry-run to see what commands would be run, without actually running anything.");18 execFunction.echo("");19 execFunction.echo("See https://github.com/folkforms/docker-tasks for readme.");20 execFunction.echo("");21 };22 // Handle args23 const option = args.splice(0, 1)[0];24 if (!option) {25 execFunction.echo("ERROR: No option chosen.");26 execFunction.echo("");27 printHelpText();28 return 1;29 }30 let version;31 if (option === "release") {32 version = args.splice(0, 1)[0];33 }34 if (option === "help") {35 printHelpText();36 return 0;37 }38 let prune = false;39 let publicRelease = false;40 let privateRelease = false;41 for (let i = 0; i < args.length; i++) {42 if (args[i] === "-p" || args[i] === "--prune") {43 prune = true;44 args.splice(i, 1);45 i--;46 continue;47 }48 if (args[i] === "--public") {49 publicRelease = true;50 args.splice(i, 1);51 i--;52 continue;53 }54 if (args[i] === "--private") {55 privateRelease = true;56 args.splice(i, 1);57 i--;58 continue;59 }60 }61 // Grab additional args62 let additionalArgs = [];63 for (let i = 0; i < args.length; i++) {64 additionalArgs.push(args[i]);65 }66 additionalArgs = additionalArgs.join(" ");67 if (option === "genconfig") {68 const cmd1 = "./node_modules/docker-tasks/.docker-tasks-default-config.yml";69 const cmd2 = "./.docker-tasks.yml";70 const r = execFunction.cp(cmd1, cmd2);71 if (r.code) {72 execFunction.echo(`ERROR: Could not copy file '${cmd1}' to '${cmd2}'.`);73 return 1;74 }75 execFunction.echo("Created file .docker-tasks.yml. You need to edit this file with your project details.");76 return 0;77 }78 /**79 * Validates that the given configuration properties exist.80 *81 * @param {...string} propNames properties to validate82 */83 const validate = (...propNames) => {84 let missingProps = [];85 propNames.forEach((propName) => {86 if (!props[propName]) {87 missingProps.push(propName);88 }89 });90 if (missingProps.length > 0) {91 execFunction.echo(`ERROR: Missing configuration properties: ${missingProps.join(", ")}`);92 return 1;93 }94 };95 /**96 * Executes the given command.97 *98 * @param {string} cmd command to execute99 */100 const exec = (cmd) => {101 cmd = cmd.replace(/\s+/g, " ");102 const r = execFunction.exec(cmd);103 if (r.code) {104 execFunction.echo(`ERROR: Could not run command: '${cmd}'.`);105 return 1;106 }107 return 0;108 };109 // Handle commands110 if (option === "build") {111 const r0 = validate("imageName");112 if (r0) {113 return r0;114 }115 let r1;116 if (prune) {117 r1 = exec(`docker system prune --force`);118 }119 if (r1) {120 return r1;121 }122 return exec(`docker build ${additionalArgs} --tag ${props.imageName}:latest .`);123 }124 if (option === "prune") {125 return exec(`docker system prune --force ${additionalArgs}`);126 }127 if (option === "run") {128 const r0 = validate("imageName");129 if (r0) {130 return r0;131 }132 exec(`docker stop ${props.imageName}`);133 exec(`docker rm ${props.imageName}`);134 const runArgs = props.runArgs || "";135 return exec(`docker run ${additionalArgs} ${runArgs} --name ${props.imageName} ${props.imageName}:latest`);136 }137 if (option === "clear") {138 const r0 = validate("imageName");139 if (r0) {140 return r0;141 }142 const r1 = exec(`docker stop ${props.imageName}`);143 if (r1) {144 return r1;145 }146 return exec(`docker rm ${props.imageName}`);147 }148 if (option === "debug") {149 const r0 = validate("imageName");150 if (r0) {151 return r0;152 }153 // FIXME Is there any way to make this work?154 execFunction.echo("We can't debug directly because we are inside a script. You need to run one of these commands:");155 execFunction.echo("");156 execFunction.echo(` docker exec --tty --interactive ${props.imageName} bash`);157 execFunction.echo(` docker run ${additionalArgs} --tty --interactive --entrypoint bash ${props.imageName}:latest`);158 execFunction.echo("");159 execFunction.echo("The first command will run bash in a running container, the second will start a new container.");160 execFunction.echo("");161 return 0;162 }163 if (option === "release") {164 if (!version) {165 execFunction.echo("ERROR: Must include a version when using 'release' option, e.g. \"yarn docker release 1.0.0\".");166 return 1;167 }168 // Release type defaults to public if not specified in config. Default can be overridden with "--public" or "--private".169 let isPublicRelease = props.defaultRelease !== "private";170 if (publicRelease) {171 isPublicRelease = true;172 }173 if (privateRelease) {174 isPublicRelease = false;175 }176 let cmds = [];177 if (isPublicRelease) {178 const r0 = validate("imageName", "username");179 if (r0) {180 return r0;181 }182 if (version !== "latest") {183 cmds.push(`docker image tag ${additionalArgs} ${props.imageName}:latest ${props.imageName}:${version}`);184 }185 cmds.push(`docker image tag ${additionalArgs} ${props.imageName}:latest docker.io/${props.username}/${props.imageName}:${version}`);186 cmds.push(`docker image push ${additionalArgs} docker.io/${props.username}/${props.imageName}:${version}`);187 } else {188 const r0 = validate("imageName", "privateRepoUrl", "privateRepoFolder");189 if (r0) {190 return r0;191 }192 if (version !== "latest") {193 cmds.push(`docker image tag ${additionalArgs} ${props.imageName}:latest ${props.imageName}:${version}`);194 }195 cmds.push(`docker image tag ${additionalArgs} ${props.imageName}:latest ${props.privateRepoUrl}/${props.privateRepoFolder}/${props.imageName}:${version}`);196 cmds.push(`docker image push ${additionalArgs} ${props.privateRepoUrl}/${props.privateRepoFolder}/${props.imageName}:${version}`);197 }198 for (let i = 0; i < cmds.length; i++) {199 exec(cmds[i]);200 }201 return 0;202 }203 execFunction.echo(`ERROR: Unknown option '${option}'.`);204 execFunction.echo("");205 printHelpText();206 return 1;207};...
animation.js
Source:animation.js
...58 );59 });60 tween.delay(10).start();61 tween.onComplete(() => {62 execFunction(callback);63 });64};65/**66 * @description å¨è½½å
¥æ¨¡ååæ§è¡å¨ç»ï¼ä¸è¬ç¨äºç¹å»æ¥¼å±è¿å
¥æ¥¼å±å
é¨ä¿¡æ¯æ¶ä½¿ç¨67 * @param {object} target ç®æ é项68 * @param {function} success å¨ç»æ§è¡ãå è½½å®æåçåè°ï¼å¨ç»åå è½½æ¯åæ¶è¿è¡çï¼åªæ两个é½å®æäºæä¼æ§è¡æååè°69 */70export const aniBeforeLoad = (target, success) => {71 let meshChangeFunc = null;72 // å®æå¨ä½ç generate å½æ°ï¼ç¨äºä¿è¯å¨ç»åè½½å
¥é½å®ææ¶æ§è¡æä½73 const step = (function* () {74 yield 'step1';75 execFunction(meshChangeFunc);76 execFunction(target.afterLoad);77 if (target.router && target.router.in) {78 vue.router.push(target.router.in);79 }80 if (target.cameraPosition) {81 lookCamera(...target.cameraPosition);82 }83 execFunction(success);84 execFunction(target.afterIn);85 execFunction(target.complete);86 })();87 execFunction(target.beforeIn);88 if (target.animate) {89 const ani = target.animate;90 const option = {91 end: formatAnimateParam(ani.target, ani.position)92 };93 Object.keys(ani).forEach(key => {94 if (!['target', 'position'].includes(key)) {95 option[key] = ani[key];96 }97 });98 execFunction(target.beforeAni);99 cameraAnimate(option, () => {100 execFunction(target.afterAni);101 step.next();102 });103 } else {104 step.next();105 }106 execFunction(target.beforeLoad);107 loadModels({108 list: target.meshList,109 success (models, meshChange) {110 meshChangeFunc = meshChange;111 step.next();112 }113 });114};115/**116 * @description å¨è½½å
¥æ¨¡ååæ§è¡å¨ç»ï¼ä¸è¬ç¨äºæ¥¼å±å
é¨éå大åºæ¯æ¶ä½¿ç¨117 * @param {object} target ç®æ é项118 * @param {function} success å è½½å®æåçåè°119 */120export const aniAfterLoad = (target, success) => {121 execFunction(target.beforeBack);122 loadModels({123 list: target.meshList,124 success (models, meshChange) {125 execFunction(meshChange);126 if (target.router && target.router.out) {127 vue.router.push(target.router.out);128 }129 execFunction(success);130 execFunction(target.afterBack);131 const ani = target.animate;132 if (ani) {133 lookCamera(ani.target, ani.position);134 const option = {135 end: formatAnimateParam(...target.cameraPosition)136 };137 Object.keys(ani).forEach(key => {138 if (!['target', 'position'].includes(key)) {139 option[key] = ani[key];140 }141 });142 cameraAnimate(option, () => {143 execFunction(target.complete);144 });145 } else {146 lookCamera(...target.cameraPosition);147 execFunction(target.complete);148 }149 }150 });151};152export default {153 lookCamera,154 formatAnimateParam,155 cameraAnimate,156 aniBeforeLoad,157 aniAfterLoad...
main.js
Source:main.js
1const readline = require("readline");2const utils = require("./Scripts/utils.js");3const { data } = require("./Scripts/data.js");4const { cls, commands, procesCmd } = data;5//Torrent (Seedbox) Functions6const add_t = require("./Scripts/Seedbox/add_t.js");7const delete_t = require("./Scripts/Seedbox/delete_t.js");8const download_t = require("./Scripts/Seedbox/download_t.js");9const fetch_t = require("./Scripts/Seedbox/fetch_t.js");10const show_t = require("./Scripts/Seedbox/show_t.js");11const zip_t = require("./Scripts/Seedbox/zip_t.js");12//Files (Downloader) Functions13const add_d = require("./Scripts/Downloader/add_d.js");14const delete_d = require("./Scripts/Downloader/delete_d.js");15const download_d = require("./Scripts/Downloader/download_d.js");16const fetch_d = require("./Scripts/Downloader/fetch_d.js");17const show_d = require("./Scripts/Downloader/show_d.js");18//Appauth Functions for app authorization19const appRegister = require("./Scripts/Appauth/register_app.js");20const accessToken = require("./Scripts/Appauth/access_token.js");21const refreshToken = require("./Scripts/Appauth/refresh_token.js");22const mainAuth = require("./Scripts/Appauth/mainAuth.js");23let torrentsInfo, filesInfo, torrents, files;24const init = async () => {25 //Waiting Screen26 cls();27 console.log("Please Wait ....\nGetting Data from internet.");28 //For fecting Data29 const fetchData = async (fetchFunction) => {30 const data = await fetchFunction()31 .then((receivedData) => receivedData)32 .catch((err) => {33 cls();34 console.log(err);35 process.exit();36 });37 return data;38 };39 //Fetches data40 torrentsInfo = await fetchData(fetch_t.fetch);41 filesInfo = await fetchData(fetch_d.fetch);42 //For faking empty data scenario (for testing purposes)43 // filesInfo={success:true,value:[]}44 // torrentsInfo={success:true,value:[]}45 //Executes mainscreen after fetching data46 if (torrentsInfo.success && filesInfo.success) {47 torrents = torrentsInfo.value;48 files = filesInfo.value;49 torrents.sort((a, b) => a.name.localeCompare(b.name));50 files.sort((a, b) => a.name.localeCompare(b.name));51 //Writes data (test data) for testing52 data.writeFile(53 __dirname + "/Scripts/Seedbox/Data/testdata.json",54 JSON.stringify(torrents)55 );56 data.writeFile(57 __dirname + "/Scripts/Downloader/Data/testdata.json",58 JSON.stringify(files)59 );60 //refreshes torrents data (local data)61 add_t.refreshData(torrents);62 mainScreen();63 } else if (64 (torrentsInfo.error && torrentsInfo.error === "badToken") ||65 (filesInfo.error && filesInfo.error === "badToken")66 )67 mainAuth.mainScreen();68 else {69 cls();70 console.log("Data Fetching error\n");71 }72};73const mainScreen = () => {74 //Data Including executing fuctions and feature name75 const featuresData = {76 seedbox: [77 {78 message: "Download Torrents",79 execFunction: download_t.mainScreen,80 },81 {82 message: "Show Torrents",83 execFunction: show_t.mainScreen,84 },85 {86 message: "Add Torrents",87 execFunction: add_t.mainScreen,88 },89 {90 message: "Remove Torrents",91 execFunction: delete_t.mainScreen,92 },93 {94 message: "ZIP Torrents",95 execFunction: zip_t.mainScreen,96 },97 ],98 downloader: [99 {100 message: "Download Files",101 execFunction: download_d.mainScreen,102 },103 {104 message: "Show Files",105 execFunction: show_d.mainScreen,106 },107 {108 message: "Add Files",109 execFunction: add_d.mainScreen,110 },111 {112 message: "Remove Files",113 execFunction: delete_d.mainScreen,114 },115 ],116 appauth: [117 {118 message: "Register App",119 execFunction: appRegister.makeRequest,120 },121 {122 message: "Get AccessToken",123 execFunction: accessToken.makeRequest,124 },125 {126 message: "Refresh AccessToken",127 execFunction: refreshToken.makeRequest,128 },129 ],130 getSectionsData: function () {131 sections = [this.seedbox, this.downloader, this.appauth];132 sectionsLength = [];133 sectionsData = [torrents, files, false];134 let t = 0;135 for (let i = 0; i < sections.length; i += 1) {136 t += sections[i].length;137 sectionsLength.push(t);138 }139 return [sections, sectionsLength, sectionsData];140 },141 sectionsBanner: ["Torrents:", "Downloads:", "App Authorization:"],142 inputScreen: function () {143 let str = "";144 str += "\t\tDebrid-Link API\n\n";145 let [sections, sectionsLength] = this.getSectionsData();146 for (let i = 0; i < sections.length; i += 1) {147 str += "\n\t " + this.sectionsBanner[i] + "\n\n";148 let j = 1;149 if (i > 0) j = sectionsLength[i - 1] + 1;150 sections[i].forEach((section, i) => {151 str += (i + j).toString() + ". " + section.message + "\n";152 });153 }154 str +=155 "\nCommmands =>\ne/exit: To exit\nr/reprint: To reprint current screen\n\n" +156 "Enter Choice:";157 return str;158 },159 };160 utils.mainMenuExec(featuresData);161};...
components.toolbarButtons.events.js
Source:components.toolbarButtons.events.js
1/*2 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.3 * http://www.jaspersoft.com.4 *5 * Unless you have purchased a commercial license agreement from Jaspersoft,6 * the following license terms apply:7 *8 * This program is free software: you can redistribute it and/or modify9 * it under the terms of the GNU Affero General Public License as10 * published by the Free Software Foundation, either version 3 of the11 * License, or (at your option) any later version.12 *13 * This program is distributed in the hope that it will be useful,14 * but WITHOUT ANY WARRANTY; without even the implied warranty of15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the16 * GNU Affero General Public License for more details.17 *18 * You should have received a copy of the GNU Affero General Public License19 * along with this program. If not, see <http://www.gnu.org/licenses/>.20 */21toolbarButtonModule.initialize = function(actionMap){22 toolbarButtonModule.actionMap = actionMap;23 jQuery('.toolbar').on('mouseup mouseover mouseout','button',function(evt){24 if(!jQuery(this).prop('disabled'))toolbarButtonModule['mouse' + evt.type.substring(5,6).toUpperCase() + evt.type.substring(6) + 'Handler'](evt,this);25 });26 if (isFirefox()) { // workaround for Bug 2622327 jQuery(".toolbar li").each(function(index,li){28 jQuery(li).css("padding", "0 2px");29 });30 }31};32toolbarButtonModule.mouseUpHandler = function(evt,el){33 /*34 if (element.hasClassName(toolbarButtonModule.CAPSULE_PATTERN)) {35 var elementId = element.readAttribute("id");36 var execFunction = toolbarButtonModule.actionMap[elementId];37 if (execFunction) {38 var executableFunction = getAsFunction(execFunction);39 executableFunction(evt);40 evt.stop();41 }42 }43 */44 var execFunction = el.className.indexOf('capsule') >= 0 ? toolbarButtonModule.actionMap[el.id] : null;45 if (execFunction) {46 var executableFunction = getAsFunction(execFunction);47 executableFunction(evt);48 evt.stopPropagation();49 }50};51toolbarButtonModule.mouseOverHandler = function(evt,el){52 /*53 if (element.hasClassName(toolbarButtonModule.CAPSULE_PATTERN)) {54 if (element.hasClassName("mutton") && !buttonManager.isDisabled(element)) {55 toolbarButtonModule.showButtonMenu(evt, element);56 }57 }58 */59 if(el.className.indexOf('capsule') >= 0 && el.className.indexOf('mutton') >= 0 && !buttonManager.isDisabled(el)){60 toolbarButtonModule.showButtonMenu(evt.originalEvent,el);61 }62};...
Functions.js
Source:Functions.js
1class Functions {2 static functions = {3 // trigonometric4 sin: args => Functions.execFunction(Math.sin, args),5 cos: args => Functions.execFunction(Math.cos, args),6 tan: args => Functions.execFunction(Math.tan, args),7 ctg: args => Functions.execFunction(Functions.ctg, args),8 asin: args => Functions.execFunction(Math.asin, args),9 acos: args => Functions.execFunction(Math.acos, args),10 atan: args => Functions.execFunction(Math.atan, args),11 asinh: args => Functions.execFunction(Math.asinh, args),12 acosh: args => Functions.execFunction(Math.acosh, args),13 atanh: args => Functions.execFunction(Math.atanh, args),14 atan2: args => Functions.execFunction(Math.atan2, args),15 // logarithmic16 sqrt: args => Functions.execFunction(Math.sqrt, args),17 cbrt: args => Functions.execFunction(Math.cbrt, args),18 exp: args => Functions.execFunction(Math.exp, args),19 ln: args => Functions.execFunction(Math.log, args),20 lg: args => Functions.execFunction(Math.log10, args),21 log10: args => Functions.execFunction(Math.log10, args),22 log2: args => Functions.execFunction(Math.log2, args),23 pow: args => Functions.execFunction(Math.pow, args),24 // other25 fact: args => Functions.execFunction(Functions.fact, args),26 factFloat: args => Functions.execFunction(Functions.factFloat, args),27 percent: args => Functions.execFunction(Functions.percent, args),28 };29 static percent(x, y) {30 return (x/100)*y;31 }32 static fact(x) {33 if (x < 0) {34 throw new Error('Factorial of negative numbers is not exists!');35 }36 let value=1;37 for (let i = 2; i <= x; i++)38 value = value * i;39 return value;40 }41 static factFloat(x) {42 if (x < 0) {43 throw new Error('Factorial of negative numbers is not exists!');44 }45 return Math.sqrt(2 * Math.PI * x) * Math.pow((x / Math.E), x) * Math.exp(1 / (12 * x) - 1 / (360 * x * x * x));46 }47 static ctg(x) {48 return 1 / Math.tan(x);49 }50 static execFunction(func, args) {51 return func(...args);52 }53 static isExists(key) {54 return Functions.functions.hasOwnProperty(key);55 }56 static get(key) {57 if (!this.isExists(key)) {58 throw new Error('Unknown function ' + key);59 } else {60 return Functions.functions[key];61 }62 }63 static set(key, value) {64 Functions.functions[key] = value;...
services.js
Source:services.js
...21 });22}23export async function changeRoles(body, execFunction) {24 if (useMockData) {25 execFunction();26 return await _sleep();27 }28 const changeRolesUrl = BASE_URL + API_ENDPOINTS.changeRoles;29 !Auth.isSignedIn() && redirectTo.login();30 return await HttpRequest.post(changeRolesUrl, body).then(execFunction);31}32export async function createGroup(body, state, execFunction) {33 if (useMockData) {34 execFunction(Math.max(state.groups.map(x => x.id)) + 1);35 return await _sleep();36 }37 const createGroupUrl = BASE_URL + API_ENDPOINTS.createGroup;38 !Auth.isSignedIn() && redirectTo.login();39 return await HttpRequest.post(createGroupUrl, body).then(execFunction);40}41export async function createCS(body, state, execFunction) {42 if (useMockData) {43 execFunction(Math.max(state.compSugg.map(x => x.id)) + 1);44 return await _sleep();45 }46 const createGroupUrl = BASE_URL + API_ENDPOINTS.createCS;47 !Auth.isSignedIn() && redirectTo.login();48 return await HttpRequest.post(createGroupUrl, body).then(execFunction);49}50export function getCurrentUserId() {51 if (useMockData) return 1;52 return AuthStore.userId;53}54export function getRandomNumber(min = 10, max = 500) {55 return Math.round(min - 0.5 + Math.random() * (max - min + 1));...
index.js
Source:index.js
...4 dfsStep(adjacencyList, startNodeIndex, visitedNodes, execFunction);5};6function dfsStep(adjacencyList, currentNodeIndex, visitedNodes, execFunction) {7 const currentNode = adjacencyList[currentNodeIndex];8 currentNode[0] = execFunction(currentNode[0]);9 for (let i = 1; i < currentNode.length; i++) {10 if (!visitedNodes[currentNode[i]]) {11 visitedNodes[currentNode[i]] = true;12 dfsStep(adjacencyList, currentNode[i], visitedNodes, execFunction);13 }14 }...
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!