Best JavaScript code snippet using jest
script.js
Source:script.js
...61 setTimeout(() => { algoDropdown.style.animation = '' }, 400)62 return63 }64 clearThePath()65 freezeConsole('freeze')66 if (chosenAlgorithm === 'a*') { modelAStar(startingPoint) }67 if (chosenAlgorithm === 'dijktras') {68 modelDijkstra(startingPoint)69 dijktraTimer()70 }71 startingPoint = document.querySelector('.start')72 if (chosenAlgorithm === 'bfs') { modelBFS(startingPoint) }73 if (chosenAlgorithm === 'dfs') { modelDFS(startingPoint) }74})75// Inability to Find A Path76function noPathVisible() {77 freezeConsole('unfreeze')78}79// Freezing the Console When Necessarry80function freezeConsole(command) {81 let toBeClassed = [findThePathBtn, clearPathBtn, clearBoardBtn, mazeDropdown, speedDropdown, algoDropdown, resetStartNodeBtn, resetEndNodeBtn]82 let toBeFrozen = [sideConsole, theConsole, theMaze]83 if (command === 'freeze') {84 toBeFrozen.forEach(section => { section.style.pointerEvents = 'none' })85 toBeClassed.forEach(element => { element.classList.add('orangefont') })86 }87 if (command === 'unfreeze') {88 toBeFrozen.forEach(section => { section.style.pointerEvents = 'auto' })89 toBeClassed.forEach(element => { element.classList.remove('orangefont') })90 }91}92// The Main and Side Console Instrcutions93const mainInstructions = document.querySelector('[main-instructions]')94const sideInstructions = document.querySelector('[side-console-instructions]')...
runTest.js
Source:runTest.js
...30type RunTestInternalResult = {31 leakDetector: ?LeakDetector,32 result: TestResult,33};34function freezeConsole(35 testConsole: BufferedConsole | Console | NullConsole,36 config: ProjectConfig,37) {38 // $FlowFixMe: overwrite it for pretty errors39 testConsole._log = function fakeConsolePush(_type, message) {40 const error = new ErrorWithStack(41 `${chalk.red(42 `${chalk.bold(43 'Cannot log after tests are done.',44 )} Did you forget to wait for something async in your test?`,45 )}\nAttempted to log "${message}".`,46 fakeConsolePush,47 );48 const formattedError = formatExecError(49 error,50 config,51 {noStackTrace: false},52 undefined,53 true,54 );55 process.stderr.write('\n' + formattedError + '\n');56 // TODO: set exit code in Jest 2557 // process.exitCode = 1;58 };59}60// Keeping the core of "runTest" as a separate function (as "runTestInternal")61// is key to be able to detect memory leaks. Since all variables are local to62// the function, when "runTestInternal" finishes its execution, they can all be63// freed, UNLESS something else is leaking them (and that's why we can detect64// the leak!).65//66// If we had all the code in a single function, we should manually nullify all67// references to verify if there is a leak, which is not maintainable and error68// prone. That's why "runTestInternal" CANNOT be inlined inside "runTest".69async function runTestInternal(70 path: Path,71 globalConfig: GlobalConfig,72 config: ProjectConfig,73 resolver: Resolver,74): Promise<RunTestInternalResult> {75 const testSource = fs.readFileSync(path, 'utf8');76 const parsedDocblock = docblock.parse(docblock.extract(testSource));77 const customEnvironment = parsedDocblock['jest-environment'];78 let testEnvironment = config.testEnvironment;79 if (customEnvironment) {80 testEnvironment = getTestEnvironment({81 ...config,82 // $FlowFixMe83 testEnvironment: customEnvironment,84 });85 }86 /* $FlowFixMe */87 const TestEnvironment = (require(testEnvironment): EnvironmentClass);88 const testFramework = ((process.env.JEST_CIRCUS === '1'89 ? require('jest-circus/runner') // eslint-disable-line import/no-extraneous-dependencies90 : /* $FlowFixMe */91 require(config.testRunner)): TestFramework);92 const Runtime = ((config.moduleLoader93 ? /* $FlowFixMe */94 require(config.moduleLoader)95 : require('jest-runtime')): Class<RuntimeClass>);96 let runtime = undefined;97 const consoleOut = globalConfig.useStderr ? process.stderr : process.stdout;98 const consoleFormatter = (type, message) =>99 getConsoleOutput(100 config.cwd,101 !!globalConfig.verbose,102 // 4 = the console call is buried 4 stack frames deep103 BufferedConsole.write(104 [],105 type,106 message,107 4,108 runtime && runtime.getSourceMaps(),109 ),110 );111 let testConsole;112 if (globalConfig.silent) {113 testConsole = new NullConsole(consoleOut, process.stderr, consoleFormatter);114 } else if (globalConfig.verbose) {115 testConsole = new Console(consoleOut, process.stderr, consoleFormatter);116 } else {117 testConsole = new BufferedConsole(() => runtime && runtime.getSourceMaps());118 }119 const environment = new TestEnvironment(config, {120 console: testConsole,121 testPath: path,122 });123 const leakDetector = config.detectLeaks124 ? new LeakDetector(environment)125 : null;126 const cacheFS = {[path]: testSource};127 setGlobal(environment.global, 'console', testConsole);128 runtime = new Runtime(config, environment, resolver, cacheFS, {129 collectCoverage: globalConfig.collectCoverage,130 collectCoverageFrom: globalConfig.collectCoverageFrom,131 collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom,132 });133 const start = Date.now();134 const sourcemapOptions = {135 environment: 'node',136 handleUncaughtExceptions: false,137 retrieveSourceMap: source => {138 const sourceMaps = runtime && runtime.getSourceMaps();139 const sourceMapSource = sourceMaps && sourceMaps[source];140 if (sourceMapSource) {141 try {142 return {143 map: JSON.parse(fs.readFileSync(sourceMapSource)),144 url: source,145 };146 } catch (e) {}147 }148 return null;149 },150 };151 // For tests152 runtime153 .requireInternalModule(154 require.resolve('source-map-support'),155 'source-map-support',156 )157 .install(sourcemapOptions);158 // For runtime errors159 sourcemapSupport.install(sourcemapOptions);160 if (161 environment.global &&162 environment.global.process &&163 environment.global.process.exit164 ) {165 const realExit = environment.global.process.exit;166 environment.global.process.exit = function exit(...args) {167 const error = new ErrorWithStack(168 `process.exit called with "${args.join(', ')}"`,169 exit,170 );171 const formattedError = formatExecError(172 error,173 config,174 {noStackTrace: false},175 undefined,176 true,177 );178 process.stderr.write(formattedError);179 return realExit(...args);180 };181 }182 try {183 await environment.setup();184 let result: TestResult;185 try {186 result = await testFramework(187 globalConfig,188 config,189 environment,190 runtime,191 path,192 );193 } catch (err) {194 // Access stack before uninstalling sourcemaps195 err.stack;196 throw err;197 }198 freezeConsole(testConsole, config);199 const testCount =200 result.numPassingTests +201 result.numFailingTests +202 result.numPendingTests +203 result.numTodoTests;204 result.perfStats = {end: Date.now(), start};205 result.testFilePath = path;206 result.coverage = runtime.getAllCoverageInfoCopy();207 result.sourceMaps = runtime.getSourceMapInfo(208 new Set(Object.keys(result.coverage || {})),209 );210 result.console = testConsole.getBuffer();211 result.skipped = testCount === result.numPendingTests;212 result.displayName = config.displayName;...
aStar.js
Source:aStar.js
...118 let reversed = array.reverse()119 let counter = 0120 const ligthUpPath = setInterval(() => {121 if (counter === reversed.length - 1) {122 setTimeout(() => { freezeConsole('unfreeze') }, 300)123 shortestPath = []124 clearInterval(ligthUpPath)125 }126 reversed[counter].classList.add('path-square')127 counter += 1128 }, 15)129}...
mazes.js
Source:mazes.js
1import { startingPoint, endingPoint, clearTheBoard, freezeConsole } from '../script.js'2// Staircase Model 3function generateStairCase() {4 freezeConsole('freeze')5 clearTheBoard()6 let up = 27 let down = 28 const downstairs = setInterval(() => {9 if (up === 20) {10 document.querySelector('.start').classList.remove('obstacle')11 document.querySelector('.ending').classList.remove('obstacle')12 clearInterval(downstairs)13 }14 document.getElementById(`${up + (up - 2) * 40}`).classList.add('obstacle')15 up += 116 }, 20)17 const upstairs = setInterval(() => {18 if (down === 19) {19 document.querySelector('.start').classList.remove('obstacle')20 document.querySelector('.ending').classList.remove('obstacle')21 freezeConsole('unfreeze')22 clearInterval(upstairs)23 }24 document.getElementById(`${740 - (down - 2) * 39}`).classList.add('obstacle')25 down += 126 }, 20)27}28// Random Maze Generation29function generateRandomMaze() {30 freezeConsole('freeze')31 clearTheBoard()32 let allSquares = Array.from(document.querySelectorAll('.square'))33 for (let i = 0; i < allSquares.length; i++) {34 let random = Math.floor(Math.random() * 4)35 if (random === 1) { allSquares[i].classList.add('obstacle') }36 }37 document.querySelector('.start').classList.remove('obstacle')38 document.querySelector('.ending').classList.remove('obstacle')39 freezeConsole('unfreeze')40}41// Vertical Maze Generation42function generateVerticalMaze() {43 freezeConsole('freeze')44 clearTheBoard()45 for (let i = 0; i < 40; i++) {46 document.getElementById(`${i}`).classList.add('obstacle')47 document.getElementById(`${760 + i}`).classList.add('obstacle')48 }49 for (let i = 1; i < 20; i++) {50 document.getElementById(`${i * 40}`).classList.add('obstacle')51 document.getElementById(`${(i * 40) - 1}`).classList.add('obstacle')52 }53 let ceiling = []54 for (let i = 1; i < 38; i++) {55 ceiling.push(document.getElementById(`${i}`))56 }57 divideEm(ceiling)58}59function divideEm(array) {60 for (let i = 0; i < array.length; i++) {61 let number = (Number(array[i].getAttribute('id')))62 if (number % 4 === 0) {63 let wall = []64 for (let j = 1; j < 19; j++) {65 document.getElementById(`${number + j * 40}`).classList.add('obstacle')66 wall.push(document.getElementById(`${number + j * 40}`))67 }68 generateGaps(wall)69 }70 }71}72function generateGaps(array) {73 let random1 = Math.floor(Math.random() * array.length)74 let a = 275 if (array.length === 2) { a = 1 }76 for (let i = 0; i < a; i++) {77 if (random1 === array.length - 1) { array[random1 - 1 - i].classList.remove('obstacle') }78 if (random1 !== array.length - 1) { array[random1 + i].classList.remove('obstacle') }79 }80 horizontalDivison(array)81}82function horizontalDivison(array) {83 for (let i = 0; i < array.length; i++) {84 if (!array[i].classList.contains('obstacle') || i % 3 !== 1) { continue }85 let random = Math.floor(Math.random() * 2)86 if (random === 0) { setTimeout(() => { pivotHorizontally(array[i], 'right') }, 500) }87 if (random === 1) { setTimeout(() => { pivotHorizontally(array[i], 'left') }, 500) }88 }89}90function pivotHorizontally(element, direction) {91 if (direction === 'left') {92 let tip93 for (let i = 0; i < 3; i++) {94 let number = Number(element.getAttribute('id'))95 if (myNeighboor(document.getElementById(`${number - i}`), 'left')) {96 document.getElementById(`${number - i}`).classList.add('obstacle')97 tip = document.getElementById(`${number - i}`)98 }99 }100 pivotVertically(tip)101 }102 if (direction === 'right') {103 let tip104 for (let i = 0; i < 3; i++) {105 let number = Number(element.getAttribute('id'))106 if (myNeighboor(document.getElementById(`${number + i}`), 'right')) {107 document.getElementById(`${number + i}`).classList.add('obstacle')108 tip = document.getElementById(`${number + i}`)109 }110 }111 pivotVertically(tip)112 }113}114function pivotVertically(element) {115 let center = Number(element.getAttribute('id'))116 for (let i = 0; i < 4; i++) {117 if (center % 40 === 37) { continue }118 let upper = document.getElementById(`${center - i * 40}`)119 if (myNeighboor(upper, 'upper')) { upper.classList.add('obstacle') }120 }121 for (let i = 0; i < 4; i++) {122 if (center % 40 === 37) { continue }123 let lower = document.getElementById(`${center + i * 40}`)124 if (myNeighboor(lower, 'lower')) { lower.classList.add('obstacle') }125 }126 startingPoint.classList.remove('obstacle')127 endingPoint.classList.remove('obstacle')128 freezeConsole('unfreeze')129}130function myNeighboor(element, direction) {131 if (element === null) { return false }132 let center = Number(element.getAttribute('id'))133 let state = true134 if (direction === 'left') {135 let left = document.getElementById(`${center - 1}`)136 if (left.classList.contains('obstacle')) { state = false }137 }138 if (direction === 'right') {139 let right = document.getElementById(`${center + 1}`)140 if (right.classList.contains('obstacle')) { state = false }141 }142 if (direction === 'upper') {...
recursiveDivision.js
Source:recursiveDivision.js
1import { clearTheBoard, freezeConsole } from '../script.js'2function generateFrames() {3 freezeConsole('freeze')4 clearTheBoard()5 for (let i = 0; i < 40; i++) {6 document.getElementById(i).classList.add('obstacle')7 document.getElementById(`${i + 40 * 19}`).classList.add('obstacle')8 }9 for (let i = 1; i < 19; i++) {10 document.getElementById(`${0 + i * 40}`).classList.add('obstacle')11 document.getElementById(`${39 + i * 40}`).classList.add('obstacle')12 }13 let topAndSide = [[], []]14 for (let i = 2; i < 38; i++) { topAndSide[0].push(document.getElementById(`${i + 40}`)) }15 for (let i = 2; i < 18; i++) { topAndSide[1].push(document.getElementById(`${38 + i * 40}`)) }16 recursivelyDivide(topAndSide)17}18let horizontalGap = []19let verticalGap = []20function makingGapsIn() {21 setTimeout(() => {22 horizontalGap.forEach(index => { gapMaker(index, 'horizontal') })23 verticalGap.forEach(index => { gapMaker(index, 'vertical') })24 document.querySelector('.start').classList.remove('obstacle')25 document.querySelector('.ending').classList.remove('obstacle')26 freezeConsole('unfreeze')27 horizontalGap = []28 verticalGap = []29 }, 2000)30}31function recursivelyDivide(array) {32 let random1 = Math.floor(Math.random() * 2) // Which direction shall we divide the grid33 if (array[0].length === 0 || array[1].length === 0) { return }34 if (array[0].length === 2) { random1 === 1 }35 if (array[1].length === 2) { random1 === 0 }36 let newArray1 = [[], []] // Division 137 let newArray2 = [[], []] // Division 238 if (random1 === 0) {39 let randomWall = (Math.floor(Math.random() * array[0].length))40 let randomGap = (Math.floor(Math.random() * array[1].length + 2))...
dijkstras.js
Source:dijkstras.js
...90 const anInterval = setInterval(() => {91 if (counter === array.length - 1) {92 dijktraSolution = []93 dijktraStopper = false94 setTimeout(() => { freezeConsole('unfreeze') }, 300)95 clearInterval(anInterval)96 }97 reversed[counter].classList.add('path-square')98 counter += 199 }, searchSpeed)100}...
breadthF.js
Source:breadthF.js
...62 if (counter === array.length - 1) {63 clearInterval(anInterval)64 BFSShortestPathArray = []65 bfsArray = []66 setTimeout(() => { freezeConsole('unfreeze') }, 300)67 }68 array[counter].classList.add('path-square')69 counter += 170 }, searchSpeed / 2)71}...
depthF.js
Source:depthF.js
...52 const anInterval = setInterval(() => {53 if (counter === array.length - 1) {54 dfsArray = []55 clearInterval(anInterval)56 setTimeout(() => { freezeConsole('unfreeze') }, 300)57 }58 array[counter].classList.add('path-square')59 array[counter].style.animation = 'pop-up 700ms'60 counter += 161 }, searchSpeed - 2)62}...
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!!