Best JavaScript code snippet using mocha
server.js
Source:server.js
1const express = require('express');2const bodyParser = require('body-parser');3const timeout = require('connect-timeout');4const fibonacci = require('./lib/fibonacci.js');5const memoryleak = require('./lib/memoryleak.js');6const pgp = require('./lib/pgp.js');7const isNumber = require('is-number');8const app = express();9// Fibonacci random fails10const RANDOM_MIN = 1;11const RANDOM_MAX = 156; //78 iterations until Number.MAX_SAFE_INTEGER12const HTTP_TIMEOUT = 2000; //ms13const MEM_MAX = 2e8; //~100mb, default14app15.use(bodyParser.json())16/**17 * @api {get} / Log "Hello World"18 * @apiGroup Api19 * @apiName HelloWorld20 * @apiSuccess {String} data Hello World21 */22.get('/', function(req, res, next) {23 console.log('Hello World');24 return res.status(200).json({data: 'Hello World'});25})26/**27 * @api {get} /fibonacci Fibonacci28 * @apiGroup Api29 * @apiName Fibonacci30 * @apiParam {Number} iterations Number of iterations31 * @apiParam {Boolean} [force=true] Don't quit if number > Number.MAX_SAFE_INTEGER32 * @apiSuccess {Object} data33 * @apiSuccess {Number} data.iterations Iterations done34 * @apiSuccess {Number} data.number Resulting number35 * @apiError (Error 500) error Number exceed the limit (9007199254740991)36 * @apiErrorExample Error-Response:37 * HTTP/1.1 500 Internal Error38 * {39 * "error": "Number exceed the limit (9007199254740991)",40 * "data": {41 * "iterations": 78,42 * "number": 1447233402467622043 * }44 * }45 * }46 */47.get('/fibonacci', function(req, res, next) {48 var rand = parseInt(req.query.iterations);49 if(!isNumber(rand)) {50 rand = Math.floor(Math.random() * (RANDOM_MAX - RANDOM_MIN + 1)) + RANDOM_MIN;51 }52 var f = fibonacci(rand, req.query.force || false);53 var response = {data: {}};54 if(f.error !== undefined) {55 response.error = f.error;56 res.status(500);57 } else {58 res.status(200);59 }60 response.data.iterations = f.iterations;61 response.data.number = f.number;62 return res.json(response);63})64/**65 * @api {get} /timeout Timeout66 * @apiGroup Api67 * @apiName Timeout68 * @apiParam {Number} timeout Timeout in ms69 * @apiSuccess {Object} data70 * @apiSuccess {boolean} data.timeout71 * @apiError (Error 408) error Response timeout72 */73.get('/timeout', timeout(HTTP_TIMEOUT), function(req, res, next) {74 return setTimeout(function() {75 if (req.timedout) { return false; }76 return res.status(200).json({data: {timeout: false}});77 }, req.query.timeout || HTTP_TIMEOUT);78})79/**80 * @api {get} /memoryleak Memory Leak81 * @apiGroup Api82 * @apiName MemoryLeak83 * @apiParam {Number} [interval=400] Stress interval in ms84 * @apiError (Error 500) error Memory size exceded85 */86.get('/memoryleak', function(req, res, next) {87 if (process.env.NODE_ENV === 'production') {88 return next(new Error('Route not available'))89 }90 memoryleak({interval: req.query.interval || 400, max_size: MEM_MAX}, () => next(new Error('Memory size exceded')));91})92/**93 * @api {get} /pgp PGP94 * @apiGroup Api95 * @apiName PGP96 * @apiParam {Number} [number=1] Number of key pairs to generate97 */98.get('/pgp', function(req, res, next) {99 pgp(req.query.number || 1)100 .then(keys => res.json(keys));101})102.use(function(err, req, res, next) {103 if(err) {104 console.error(err.stack);105 if(req.timedout) {106 res.status(408);107 } else {108 res.status(500);109 }110 return res.send({error: err.message});111 }112 return next()113})114.use(function(req, res, next) {115 return res.status(404).send({error: 'Not found'});116});117app.listen(3200, function() {118 console.log('Listening on 3200');...
resourceConsumer.js
Source:resourceConsumer.js
1class ResourcesConsumer {2 responseTime;3 failureRate;4 memoryLeak;5 data = [];6 requestCounter = 0;7 failureRateHelper = [];8 constructor(responseTime = 140, failureRate = 0, memoryLeak = false) {9 this.responseTime = responseTime;10 this.failureRate = failureRate;11 this.memoryLeak = memoryLeak;12 this.failureRateHelper = Array.from(13 { length: 100 },14 function (_, i) {15 if (this.fails === 0) {16 return false;17 }18 if (100 - i <= this.fails) {19 this.fails--;20 return true;21 }22 if (Math.random() < this.failureRate / 100) {23 this.fails--;24 return true;25 }26 return false;27 },28 { fails: this.failureRate },29 );30 }31 blockCPU(time = this.responseTime) {32 const now = new Date().getTime();33 const v = Math.random() * 40;34 const calculations = this.memoryLeak ? this.data : [];35 for (;;) {36 calculations.push(Math.random() * Math.random());37 if (new Date().getTime() > now + time + v) {38 return;39 }40 }41 }42 consume(computingTime = this.responseTime, errorOverhead = 0) {43 this.blockCPU(computingTime + errorOverhead);44 const throwError = this.failureRateHelper[this.requestCounter];45 this.requestCounter++;46 if (this.requestCounter === 100) {47 this.requestCounter = 0;48 }49 if (throwError) {50 throw new Error();51 }52 }53}54exports.consumeResources = (responseTime, failureRate, memoryLeak) => {55 return new ResourcesConsumer(responseTime, failureRate, memoryLeak);...
router.js
Source:router.js
1import _function from "./function.md"2import closure from "./closure.md"3import memoryLeak from "./memoryLeak.md"4import jsThis from "./this.md"5import executionStack from "./executionStack.md"6import prototype from "./prototype.md"7import _event from "./event.md"8import objectCreate from "./objectCreate";9import eventLoop from "./eventLoop";10import test from "./test.vue";11const routerPrefix = "js/";12const jsRouter = [13{path: `${routerPrefix}function`,component: _function,name:"å½æ°åºæ¬,éå½,èªæ§è¡"},14{path: `${routerPrefix}this`,component: jsThis,name:"å½æ°å
é¨å¯¹è±¡this"},15{path: `${routerPrefix}closure`,component: closure,name:"ä»ä¹æ¯éå
"},16{path: `${routerPrefix}memoryLeak`,component: memoryLeak,name:"åå¨æ³æ¼æº¢åº"},17{path: `${routerPrefix}executionStack`,component: executionStack,name:"jsæ§è¡æ ä¸ä¸ä¸æ"},18{path: `${routerPrefix}prototype`,component: prototype,name:"ååé¾,new å¹²äºä»ä¹"},19{path: `${routerPrefix}event`,component: _event,name:"eventï¼äºä»¶æµï¼äºä»¶å§æ"},20{path: `${routerPrefix}objectCreate`,component: objectCreate,name:"对象ï¼å¯¹è±¡çå建"},21{path: `${routerPrefix}eventLoop`,component: eventLoop,name:"jsè¿è¡æºå¶(eventLoop)ï¼å¾®ä»»å¡ï¼å®ä»»å¡"},22{path: `${routerPrefix}test`,component: test,name:"js æµè¯é¡µé¢"},23]24export default jsRouter;...
issue-1991.fixture.js
Source:issue-1991.fixture.js
...34 });35 it('access a variable via a closure', function () {36 // slow performance on older node.js versions37 this.timeout(1000);38 closureVar = new MemoryLeak();39 });40 });...
memoryLeak.js
Source:memoryLeak.js
1import { defineCard, Card, PlayArgs } from '../card'2import { defineEffect } from '../../effects/effect'3import { ExhaustCard } from '../../events/exhaustCard'4import { AddToHand } from '../../events/addToHand'5import { DrawCards } from '../../events/drawCards'6import { BindEnergy } from '../../events/bindEnergy'7const Drain = defineEffect(8 'drain',9 {10 name: 'Drain',11 innerColor: '#ee8866',12 outerColor: '#bb3322',13 description: 'On draw, lose 1 energy.',14 sides: 3,15 rotation: 0.5,16 },17 {18 stacked: false,19 delta: (x) => x,20 min: 1,21 max: 1,22 },23 (owner) => ({24 subjects: [owner],25 tags: [DrawCards],26 type: AddToHand,27 }),28 (owner, type) =>29 function*({ resolver, game }) {30 yield resolver.processEvent(31 new BindEnergy(owner, game.player, {32 quantity: -1,33 })34 )35 },36 [AddToHand]37)38export const MemoryLeak = defineCard(39 'memoryLeak',40 function*(self: Card<>, { energy }: PlayArgs) {41 return { energy }42 },43 {44 energy: undefined,45 },46 {47 color: '111122',48 text: '#[Unplayable]. On draw, lose 1 energy.',49 title: 'Memory Leak',50 },51 [Drain, 1]...
memory-leak.spec.js
Source:memory-leak.spec.js
...4 let source, memoryLeak;5 let doneCalled = false6 beforeEach(() => {7 source = new Subject();8 memoryLeak = new MemoryLeak(source.asObservable());9 });10 it('should always unsubscribe', done => {11 source.subscribe(() => {12 expect(memoryLeak.id).toEqual(54);13 myDone(done);14 });15 source.next(54);16 memoryLeak.unsubscribe();17 source.next(65);18 });19 function myDone(fn) {20 if (!doneCalled) {21 fn()22 console.log('DONE')...
status.js
Source:status.js
1import { Character, F, D, C, B, A } from '../../character'2import { CardLibrary } from '../cardLibrary'3import { HardwareFailure } from './hardwareFailure'4import { Deadlock } from './deadlock'5import { Interrupt } from './interupt'6import { MemoryLeak } from './memoryLeak'7const status = new Character('Status', false, '#494955', '')8status.addCard(D, HardwareFailure)9status.addCard(D, Deadlock)10status.addCard(D, Interrupt)11status.addCard(D, MemoryLeak)...
leaky.js
Source:leaky.js
1require("v8-profiler");2var leakObject = null;3function MemoryLeak() {4 var originalObject = leakObject;5 leakObject = {6 longString : new Array(1000000).join("*"),7 someMethod : function () {8 console.log(originalObject);9 }10 };11};...
Using AI Code Generation
1var assert = require('assert');2var MemoryLeak = require('mocha-memory-leak')();3describe('Memory Leak Test', function() {4 it('should not leak', function() {5 var obj = {};6 MemoryLeak.watch(obj);7 });8});9{10 "dependencies": {11 },12 "devDependencies": {13 },14 "scripts": {15 },16}
Using AI Code Generation
1var MemoryLeak = require('mocha-memory-leak')();2var assert = require('assert');3describe('Memory Leak', function() {4 it('should not leak', function() {5 var leak = new MemoryLeak();6 var a = [];7 for (var i = 0; i < 100000; i++) {8 a.push(i);9 }10 assert.ok(leak.check());11 });12});13"dependencies": {14 }15var MemoryLeak = require('mocha-memory-leak')();16var assert = require('assert');17describe('Memory Leak', function() {18 it('should not leak', function() {19 var leak = new MemoryLeak();20 assert.ok(leak.check());21 });22});
Using AI Code Generation
1global.gc();2const heapUsed = process.memoryUsage().heapUsed;3console.log(`The script uses approximately ${heapUsed} bytes of memory`);4const assert = require('assert');5const heapUsed = process.memoryUsage().heapUsed;6assert.equal(heapUsed, 0);7const assert = require('assert');8const heapUsed = process.memoryUsage().heapUsed;9assert.equal(heapUsed, 0);10const assert = require('assert');11const heapUsed = process.memoryUsage().heapUsed;12assert.equal(heapUsed, 0);13const assert = require('assert');14const heapUsed = process.memoryUsage().heapUsed;15assert.equal(heapUsed, 0);16const assert = require('assert');17const heapUsed = process.memoryUsage().heapUsed;18assert.equal(heapUsed, 0);19const assert = require('assert');20const heapUsed = process.memoryUsage().heapUsed;21assert.equal(heapUsed, 0);22const assert = require('assert');23const heapUsed = process.memoryUsage().heapUsed;24assert.equal(heapUsed, 0);25const assert = require('assert');26const heapUsed = process.memoryUsage().heapUsed;27assert.equal(heapUsed, 0);28const assert = require('assert');29const heapUsed = process.memoryUsage().heapUsed;30assert.equal(heapUsed, 0);31const assert = require('assert');32const heapUsed = process.memoryUsage().heapUsed;33assert.equal(heapUsed, 0);34const assert = require('assert');
Using AI Code Generation
1var leak = require('leak');2var memwatch = require('memwatch');3var heapdump = require('heapdump');4var memwatch = require('memwatch');5var gc = require('gc-stats')();6var heapdump = require('heapdump');7var leaky = leak({max: 10, timeout: 1000}, function (err, leak) {8 if (leak) {9 console.log('memory leak detected');10 heapdump.writeSnapshot();11 }12 else {13 console.log('no memory leak detected');14 }15});16gc.on('stats', function(stats) {17 console.log('GC: ', stats);18});19var i = 0;20var leak = setInterval(function () {21 i++;22}, 1000);23"devDependencies": {24}25Chrome > Help > About Google Chrome > Memory (Process) > Snapshot26clearInterval(leak);
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!!