Best JavaScript code snippet using jest
index.js
Source:index.js
...56 const cli = meow(cliOptions);57 const invalidOptionsMessage = checkInvalidCLIOptions(cliOptions.flags, cli.flags);58 if (invalidOptionsMessage) {59 process.stderr.write(invalidOptionsMessage);60 return exitProcess();61 }62 if (cli.flags.init) {63 return init_command()64 .then(exitProcess);65 }66 if (cli.flags.printConfig !== undefined) {67 if (cli.flags.printConfig === "") {68 console.log(chalk`A file path must be provided when using the {blue.bold print-config} option.`);69 exitProcess(EXIT_CODE_ERROR); // eslint-disable-line no-process-exit70 }71 const config = find_local_config(cli.flags.printConfig);72 if (config) {73 process.stdout.write(JSON.stringify(config.config, null, " "));74 exitProcess();75 }76 console.log(chalk`{red.bold Couldn't file a config file to print}`);77 exitProcess(true);78 }79 // use config_path if provided or search local config file80 if (cli.flags.help || cli.flags.h || argv.length === 0) {81 cli.showHelp();82 }83 return lint(cli.input, cli.flags.config);84};85function exitProcess(is_errored = false) {86 displayBetaVersionMessage();87 const exit_code = is_errored ? EXIT_CODE_ERROR : EXIT_CODE_NORMAL;88 return process.exit(exit_code);89}90async function lint(input, config_path) {91 let files_linters = [];92 const searchSpinner = ora("Searching for files").start();93 try {94 files_linters = await linthtml.create_linters_for_files(input, config_path);95 searchSpinner.succeed(`Found ${files_linters.length} files`); // deal with 096 } catch (error) {97 searchSpinner.fail();98 printErrors(error);99 exitProcess(true);100 }101 const lintSpinner = ora("Analysing files");102 try {103 lintSpinner.start();104 let reports = await Promise.all(files_linters.map(lintFile));105 reports = reports.filter(report => report.issues.length > 0);106 lintSpinner.succeed("Files analyzed");107 printReports(reports);108 } catch (error) {109 lintSpinner.fail();110 console.log();111 console.log(chalk`An error occured while analysing {underline ${error.fileName}}`);112 console.log();113 printErrors(error);114 console.log(chalk`{red ${error.message}}`);115 return exitProcess(true);116 }117}118function printReports(reports) {119 console.log();120 reports.forEach(print_file_report);121 if (reports.length > 0) {122 let issues = reports.filter((report) => report.issues.length > 0);123 issues = flatten(issues.map(_ => _.issues));124 const errorsCount = issues.reduce((count, issue) => issue.severity === "error" ? count + 1 : count, 0);125 const warningCount = issues.reduce((count, issue) => issue.severity === "warning" ? count + 1 : count, 0);126 const problemsCount = errorsCount + warningCount;127 if (errorsCount > 0) {128 console.log(chalk`{red â ${problemsCount} ${problemsCount > 1 ? "problems" : "problem"} (${errorsCount} ${errorsCount > 1 ? "errors" : "error"}, ${warningCount} ${warningCount > 1 ? "warnings" : "warning"})}`);129 displayBetaVersionMessage();130 return exitProcess(true);131 }132 console.log(chalk`{yellow â ${problemsCount} ${problemsCount > 1 ? "problems" : "problem"} (${errorsCount} ${errorsCount > 1 ? "errors" : "error"}, ${warningCount} ${warningCount > 1 ? "warnings" : "warning"})}`);133 } else {134 console.log("⨠There's no problem, good job ð");135 }136 return exitProcess();137}138async function lintFile({ file_path, linter, config_path, preset }) {139 try {140 const file_content = fs.readFileSync(file_path, "utf8");141 const issues = await linter.lint(file_content);142 return {143 fileName: file_path,144 issues,145 config_path,146 preset147 };148 } catch (error) {149 error.fileName = file_path;150 throw error;...
settings.js
Source:settings.js
...5 */6var fs = require('fs');7var path = require('path');8require('./string');9function exitProcess(reason) {10 console.error.apply(console,arguments);11 setTimeout(function() {12 process.exit();13 },20000);14}15module.exports = {16 init : function(configObj) {17 this.configObj = configObj;18 return this;19 },20 loadVar : function(key) {21 var value;22 if (key.indexOf('.') == -1) {23 value = this.configObj[key]24 } else {25 var keyArray = key.split('.');26 var keyStr = keyArray[0];27 value = this.configObj[keyStr];28 for(var i= 1,len=keyArray.length;i<len;i++) {29 if (!value && i < len-1) {30 exitProcess('the var ['+keyStr + '] is empty.');31 return undefined;32 }33 var keyNow = keyArray[i];34 keyStr += '.'+keyNow;35 value = value[keyNow];36 }37 }38 console.log('load var ['+key+'],value:',value);39 return value;40 },41 loadNecessaryVar : function(key) {42 var value = this.loadVar(key);43 if (typeof(value) =='undefined') {44 exitProcess('the value of ' + key + ' is necessary , but now is undefined');45 return false;46 }47 return value;48 },49 loadNecessaryString : function(key) {50 var str = this.loadVar(key);51 if (typeof (str) != 'string') {52 exitProcess('the value of ' + key + ' is a necessary string, but get ' + str);53 return false;54 }55 return str;56 },57 loadNecessaryInt : function(key) {58 var num = parseInt(this.loadVar(key));59 if (isNaN(num)) {60 exitProcess('the value of ' +key+' is a necessary int ,but get ' + num);61 return false;62 }63 return num;64 },65 loadNecessaryObject : function(key) {66 var obj = this.loadVar(key);67 if (!obj || typeof (obj) != 'object') {68 exitProcess('the value of ' +key+' is a necessary object ,but get ', obj);69 return false;70 }71 return obj;72 },73 loadNecessaryFile : function(key,onlyCheckDirectory) {74 var filePath = this.loadVar(key);75 if (!onlyCheckDirectory) {76 if (!fs.existsSync(filePath)) {77 exitProcess('the value of ' +key+' is a necessary file ,but not exists in '+ filePath);78 return false;79 }80 } else {81 var dirname = path.dirname(filePath);82 if (!fs.lstatSync(dirname).isDirectory()) {83 exitProcess('the path '+dirname + ' must exist and be a directory');84 return false;85 }86 }87 return filePath;88 },89 loadNecessaryDirectory : function(key,endWithSeparator) {90 var filepath = this.loadNecessaryFile(key);91 if (!fs.lstatSync(filepath).isDirectory()) {92 exitProcess('the path '+filepath + ' must be a directory');93 return false;94 }95 if (endWithSeparator && !filepath.endWith(path.sep)) {96 exitProcess('the path '+filepath + ' must be end with a separator');97 return false;98 }99 return filepath;100 },101 loadNecessaryUrl : function(key,endWithSeparator) {102 var url = this.loadNecessaryString(key);103 if (!url.startWith('http://') && !url.startWith('https://')) {104 exitProcess('invalid url');105 return false;106 }107 if (endWithSeparator && !url.endWith('/')) {108 exitProcess('the url['+url+'] must be end with /');109 return false;110 }111 if (!endWithSeparator && url.endWith('/')) {112 exitProcess('the url['+url+'] must not be end with /');113 return false;114 }115 return url;116 }...
seed-up.js
Source:seed-up.js
...36 }37};38db.dropDatabase()39 .then(async () => {40 AuthModel.insertMany(adminAuthsData, (err) => exitProcess(err, 'adminAuths'));41 AuthModel.insertMany(ngoAuthsData, (err) => exitProcess(err, 'ngoAuths'));42 AdminModel.insertMany(adminsData, (err) => exitProcess(err, 'admins'));43 SubscriberModel.insertMany(subscribersData, (err) => exitProcess(err, 'subscribers'));44 SDGModel.insertMany(sdgsData, (err) => exitProcess(err, 'sdgs'));45 NGOModel.insertMany(ngosData, (err) => exitProcess(err, 'ngos'));46 EventModel.insertMany(eventsData, (err) => exitProcess(err, 'events'));47 ProhibitedItemModel.insertMany(prohibitedItemsData, (err) => exitProcess(err, 'prohibited items'));48 DonationModel.insertMany(donationsData, (err) => exitProcess(err, 'events'));49 })50 .catch((err) => {51 logger.error(err.message);52 process.exit();...
cli.js
Source:cli.js
...5import cli from "../src/cli";6const chance = new Chance();7test("cli services-cli provides a default parameters", (t) => {8 cli()9 .exitProcess(false)10 .parse("", (err, defaults) => {11 t.is(defaults.redisHost, "localhost");12 t.is(defaults.redisPort, 6379);13 t.is(defaults.dataPath, "/tmp");14 });15});16test("cli services-cli can set arguments through the environment", (t) => {17 const expectedHost = chance.string({length: 5});18 const expectedPort = chance.natural();19 const expectedPath = chance.string({length: 5});20 process.env.TREX_REDIS_HOST = expectedHost;21 process.env.TREX_REDIS_PORT = expectedPort;22 process.env.TREX_DATA_PATH = expectedPath;23 cli()24 .exitProcess(false)25 .parse("", (err, defaults) => {26 t.is(defaults.redisHost, expectedHost);27 t.is(defaults.redisPort, expectedPort);28 t.is(defaults.dataPath, expectedPath);29 });30 ["REDIS_HOST", "REDIS_PORT", "DATA_PATH"].forEach(31 (v) => delete process.env[`TREX_${v}`],32 );33});34test("cli services-cli start needs option: service", (t) => {35 cli()36 .exitProcess(false)37 .parse("start", (err) => {38 t.true(/Missing.*: service/i.test(err.message));39 });40});41test("cli services-cli start accepts the service and port", (t) => {42 cli()43 .exitProcess(false)44 .parse("start -s service -p 667", (err, cfg) => {45 t.is(cfg.service, "service");46 t.is(cfg.port, 667);47 });48});49test("cli services-cli start has a default port", (t) => {50 cli()51 .exitProcess(false)52 .parse("start -s service", (err, cfg) => {53 t.is(cfg.port, 3000);54 });55});56[".servicesrc", ".services.json"].forEach((file) =>57 test(`cli services-cli start recognizes ${file} as a config file`, (t) => {58 mockFs({59 [file]: JSON.stringify({service: "service", port: 667}),60 });61 cli()62 .exitProcess(false)63 .parse("start", (err, cfg) => {64 t.is(cfg.service, "service");65 t.is(cfg.port, 667);66 });67 mockFs.restore();68 }),...
check-commit.js
Source:check-commit.js
...5const simpleGit = require('simple-git/promise');6const cwd = process.cwd();7const git = simpleGit(cwd);8const { version } = require(path.resolve(cwd, 'package.json'));9function exitProcess(code = 1) {10 console.log(''); // Keep an empty line here to make looks good~11 process.exit(code);12}13async function checkVersion() {14 const { versions } = await fetch('http://registry.npmjs.org/antd').then(res => res.json());15 if (version in versions) {16 console.log(chalk.yellow('ð Current version already exists. Forget update package.json?'));17 console.log(chalk.cyan(' => Current:'), version);18 exitProcess();19 }20}21async function checkBranch({ current }) {22 if (current !== 'master' && current !== '4.0-prepare') {23 console.log(chalk.yellow('ð¤ You are not in the master branch!'));24 exitProcess();25 }26}27async function checkCommit({ files }) {28 if (files.length) {29 console.log(chalk.yellow('ð You forgot something to commit.'));30 files.forEach(({ path: filePath, working_dir: mark }) => {31 console.log(' -', chalk.red(mark), filePath);32 });33 exitProcess();34 }35}36async function checkRemote() {37 const { remote } = await git.fetch('origin', 'master');38 if (remote.indexOf('ant-design/ant-design') === -1) {39 console.log(40 chalk.yellow('ð Your remote origin is not ant-design/ant-design, did you fork it?'),41 );42 exitProcess();43 }44}45async function checkAll() {46 const status = await git.status();47 await checkVersion();48 await checkBranch(status);49 await checkCommit(status);50 await checkRemote();51}...
cheatsheet.controllers.js
Source:cheatsheet.controllers.js
2const { exitProcess } = require('../utils');3const addCheatSheet = async (csheet) => {4 await CheatSheet.create(csheet);5 console.log('New Cheatsheet Created');6 exitProcess();7};8const findCheatSheet = async (word) => {9 const search = new RegExp(word, 'i');10 const cSheets = await CheatSheet.find({11 $or: [12 { kind: search },13 { title: search },14 { description: search },15 { example: search },16 ], // mongoDB $or operator17 });18 if (cSheets.length === 0 || !cSheets) {19 console.log('No cheatsheet found');20 exitProcess();21 } else {22 console.table(23 cSheets.map((cs) => ({24 kind: cs.kind,25 title: cs.title,26 description: cs.description,27 example: cs.example,28 })),29 );30 exitProcess();31 }32};33const listCheatSheet = async () => {34 const cSheets = await CheatSheet.find().lean();35 console.table(36 cSheets.map((cs) => ({37 _id: cs._id.toString(),38 kind: cs.kind,39 title: cs.title,40 description: cs.description,41 example: cs.example,42 })),43 );44 exitProcess();45};46const updateCheatSheet = async (_id, newCS) => {47 await CheatSheet.updateOne({ _id }, newCS);48 console.info('Cheatsheet Updated');49 exitProcess();50};51const removeCheatSheet = async (id) => {52 await CheatSheet.findByIdAndDelete(id);53 console.log('Cheatsheet Deleted');54 exitProcess();55};56module.exports = {57 addCheatSheet,58 findCheatSheet,59 listCheatSheet,60 removeCheatSheet,61 updateCheatSheet,...
ApiHook.js
Source:ApiHook.js
1// custom log function.2log('\n====================================================\n')3const ExitProcess = new Cmu.ApiHook(); // Create From Our Module4ExitProcess.OnCallBack = function (Emu, API,ret) {5 ExitProcess.args[0] = 1007;6 ExitProcess.args[1] = 2222;7 console.log("Hello From ExitProcess -",ExitProcess.version);8 return true;9};10ExitProcess.install('kernel32.dll', 'ExitProcess');11log('ExitProcess.args[0] : ',ExitProcess.args[0])12log('ExitProcess.args[1] : ',ExitProcess.args[1])13log('\n====================================================\n')14const MessageBox = new ApiHook(); // From the Global context15MessageBox.OnCallBack = function (Emu, API,ret) {16 MessageBox.args[0] = 'hello';17 MessageBox.args[1] = 1010;18 console.log("Hello From MessageBox",MessageBox.version);19 return false;20};21MessageBox.install('user32.dll', 'MessageBox');22log('MessageBox.args[0] : ',MessageBox.args[0])...
process-events.js
Source:process-events.js
2const packageJson = require(`../../package.json`);3const logger = require(`../logging/logger`);4process.on(`uncaughtException`, function(err) {5 logger.error(`Unhandled Error on process : `, err);6 exitProcess(1);7});8process.on(`exit`, function() {9 logger.info(packageJson.name + ` is exiting`);10});11process.on(`SIGTERM`, function() {12 logger.info(`SIGTERM received stopping processing.`);13 exitProcess(0);14});15process.on(`SIGINT`, function() {16 logger.info(`SIGINT received stopping processing.`);17 exitProcess(0);18});19function exitProcess(code) {20 // eslint-disable-next-line no-process-exit21 process.exit(code);...
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!!