Best JavaScript code snippet using ava
assert.js
Source:assert.js
...18 label,19 formatted: concordance.formatDescriptor(descriptor, concordanceOptions)20 };21}22function formatWithLabel(label, value) {23 return formatDescriptorWithLabel(label, concordance.describe(value, concordanceOptions));24}25const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);26class AssertionError extends Error {27 constructor(opts) {28 super(opts.message || '');29 this.name = 'AssertionError';30 this.assertion = opts.assertion;31 this.fixedSource = opts.fixedSource;32 this.improperUsage = opts.improperUsage || false;33 this.operator = opts.operator;34 this.values = opts.values || [];35 // Raw expected and actual objects are stored for custom reporters36 // (such as wallaby.js), that manage worker processes directly and37 // use the values for custom diff views38 this.raw = opts.raw;39 // Reserved for power-assert statements40 this.statements = [];41 if (opts.stack) {42 this.stack = opts.stack;43 } else {44 const limitBefore = Error.stackTraceLimit;45 Error.stackTraceLimit = Infinity;46 Error.captureStackTrace(this);47 Error.stackTraceLimit = limitBefore;48 }49 }50}51exports.AssertionError = AssertionError;52function getStack() {53 const limitBefore = Error.stackTraceLimit;54 Error.stackTraceLimit = Infinity;55 const obj = {};56 Error.captureStackTrace(obj, getStack);57 Error.stackTraceLimit = limitBefore;58 return obj.stack;59}60function validateExpectations(assertion, expectations, numArgs) { // eslint-disable-line complexity61 if (typeof expectations === 'function') {62 expectations = {instanceOf: expectations};63 } else if (typeof expectations === 'string' || expectations instanceof RegExp) {64 expectations = {message: expectations};65 } else if (numArgs === 1 || expectations === null) {66 expectations = {};67 } else if (typeof expectations !== 'object' || Array.isArray(expectations) || Object.keys(expectations).length === 0) {68 throw new AssertionError({69 assertion,70 message: `The second argument to \`t.${assertion}()\` must be a function, string, regular expression, expectation object or \`null\``,71 values: [formatWithLabel('Called with:', expectations)]72 });73 } else {74 if (hasOwnProperty(expectations, 'instanceOf') && typeof expectations.instanceOf !== 'function') {75 throw new AssertionError({76 assertion,77 message: `The \`instanceOf\` property of the second argument to \`t.${assertion}()\` must be a function`,78 values: [formatWithLabel('Called with:', expectations)]79 });80 }81 if (hasOwnProperty(expectations, 'message') && typeof expectations.message !== 'string' && !(expectations.message instanceof RegExp)) {82 throw new AssertionError({83 assertion,84 message: `The \`message\` property of the second argument to \`t.${assertion}()\` must be a string or regular expression`,85 values: [formatWithLabel('Called with:', expectations)]86 });87 }88 if (hasOwnProperty(expectations, 'name') && typeof expectations.name !== 'string') {89 throw new AssertionError({90 assertion,91 message: `The \`name\` property of the second argument to \`t.${assertion}()\` must be a string`,92 values: [formatWithLabel('Called with:', expectations)]93 });94 }95 if (hasOwnProperty(expectations, 'code') && typeof expectations.code !== 'string' && typeof expectations.code !== 'number') {96 throw new AssertionError({97 assertion,98 message: `The \`code\` property of the second argument to \`t.${assertion}()\` must be a string or number`,99 values: [formatWithLabel('Called with:', expectations)]100 });101 }102 for (const key of Object.keys(expectations)) {103 switch (key) {104 case 'instanceOf':105 case 'is':106 case 'message':107 case 'name':108 case 'code':109 continue;110 default:111 throw new AssertionError({112 assertion,113 message: `The second argument to \`t.${assertion}()\` contains unexpected properties`,114 values: [formatWithLabel('Called with:', expectations)]115 });116 }117 }118 }119 return expectations;120}121// Note: this function *must* throw exceptions, since it can be used122// as part of a pending assertion for promises.123function assertExpectations({assertion, actual, expectations, message, prefix, stack}) {124 if (!isError(actual)) {125 throw new AssertionError({126 assertion,127 message,128 stack,129 values: [formatWithLabel(`${prefix} exception that is not an error:`, actual)]130 });131 }132 if (hasOwnProperty(expectations, 'is') && actual !== expectations.is) {133 throw new AssertionError({134 assertion,135 message,136 stack,137 values: [138 formatWithLabel(`${prefix} unexpected exception:`, actual),139 formatWithLabel('Expected to be strictly equal to:', expectations.is)140 ]141 });142 }143 if (expectations.instanceOf && !(actual instanceof expectations.instanceOf)) {144 throw new AssertionError({145 assertion,146 message,147 stack,148 values: [149 formatWithLabel(`${prefix} unexpected exception:`, actual),150 formatWithLabel('Expected instance of:', expectations.instanceOf)151 ]152 });153 }154 if (typeof expectations.name === 'string' && actual.name !== expectations.name) {155 throw new AssertionError({156 assertion,157 message,158 stack,159 values: [160 formatWithLabel(`${prefix} unexpected exception:`, actual),161 formatWithLabel('Expected name to equal:', expectations.name)162 ]163 });164 }165 if (typeof expectations.message === 'string' && actual.message !== expectations.message) {166 throw new AssertionError({167 assertion,168 message,169 stack,170 values: [171 formatWithLabel(`${prefix} unexpected exception:`, actual),172 formatWithLabel('Expected message to equal:', expectations.message)173 ]174 });175 }176 if (expectations.message instanceof RegExp && !expectations.message.test(actual.message)) {177 throw new AssertionError({178 assertion,179 message,180 stack,181 values: [182 formatWithLabel(`${prefix} unexpected exception:`, actual),183 formatWithLabel('Expected message to match:', expectations.message)184 ]185 });186 }187 if (typeof expectations.code === 'string' && actual.code !== expectations.code) {188 throw new AssertionError({189 assertion,190 message,191 stack,192 values: [193 formatWithLabel(`${prefix} unexpected exception:`, actual),194 formatWithLabel('Expected code to equal:', expectations.code)195 ]196 });197 }198}199function wrapAssertions(callbacks) {200 const pass = callbacks.pass;201 const pending = callbacks.pending;202 const fail = callbacks.fail;203 const noop = () => {};204 const assertions = {205 pass() {206 pass(this);207 },208 fail(message) {209 fail(this, new AssertionError({210 assertion: 'fail',211 message: message || 'Test failed via `t.fail()`'212 }));213 },214 is(actual, expected, message) {215 if (Object.is(actual, expected)) {216 pass(this);217 } else {218 const result = concordance.compare(actual, expected, concordanceOptions);219 const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);220 const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);221 if (result.pass) {222 fail(this, new AssertionError({223 assertion: 'is',224 message,225 raw: {actual, expected},226 values: [formatDescriptorWithLabel('Values are deeply equal to each other, but they are not the same:', actualDescriptor)]227 }));228 } else {229 fail(this, new AssertionError({230 assertion: 'is',231 message,232 raw: {actual, expected},233 values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]234 }));235 }236 }237 },238 not(actual, expected, message) {239 if (Object.is(actual, expected)) {240 fail(this, new AssertionError({241 assertion: 'not',242 message,243 raw: {actual, expected},244 values: [formatWithLabel('Value is the same as:', actual)]245 }));246 } else {247 pass(this);248 }249 },250 deepEqual(actual, expected, message) {251 const result = concordance.compare(actual, expected, concordanceOptions);252 if (result.pass) {253 pass(this);254 } else {255 const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);256 const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);257 fail(this, new AssertionError({258 assertion: 'deepEqual',259 message,260 raw: {actual, expected},261 values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]262 }));263 }264 },265 notDeepEqual(actual, expected, message) {266 const result = concordance.compare(actual, expected, concordanceOptions);267 if (result.pass) {268 const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);269 fail(this, new AssertionError({270 assertion: 'notDeepEqual',271 message,272 raw: {actual, expected},273 values: [formatDescriptorWithLabel('Value is deeply equal:', actualDescriptor)]274 }));275 } else {276 pass(this);277 }278 },279 throws(fn, expectations, message) {280 if (typeof fn !== 'function') {281 fail(this, new AssertionError({282 assertion: 'throws',283 improperUsage: true,284 message: '`t.throws()` must be called with a function',285 values: [formatWithLabel('Called with:', fn)]286 }));287 return;288 }289 try {290 expectations = validateExpectations('throws', expectations, arguments.length);291 } catch (error) {292 fail(this, error);293 return;294 }295 let retval;296 let actual;297 let threw = false;298 try {299 retval = fn();300 if (isPromise(retval)) {301 try {302 retval.catch(noop);303 } catch (_) {}304 fail(this, new AssertionError({305 assertion: 'throws',306 message,307 values: [formatWithLabel('Function returned a promise. Use `t.throwsAsync()` instead:', retval)]308 }));309 return;310 }311 } catch (error) {312 actual = error;313 threw = true;314 }315 if (!threw) {316 fail(this, new AssertionError({317 assertion: 'throws',318 message,319 values: [formatWithLabel('Function returned:', retval)]320 }));321 return;322 }323 try {324 assertExpectations({325 assertion: 'throws',326 actual,327 expectations,328 message,329 prefix: 'Function threw'330 });331 pass(this);332 return actual;333 } catch (error) {334 fail(this, error);335 }336 },337 throwsAsync(thrower, expectations, message) {338 if (typeof thrower !== 'function' && !isPromise(thrower)) {339 fail(this, new AssertionError({340 assertion: 'throwsAsync',341 improperUsage: true,342 message: '`t.throwsAsync()` must be called with a function or promise',343 values: [formatWithLabel('Called with:', thrower)]344 }));345 return Promise.resolve();346 }347 try {348 expectations = validateExpectations('throwsAsync', expectations, arguments.length);349 } catch (error) {350 fail(this, error);351 return Promise.resolve();352 }353 const handlePromise = (promise, wasReturned) => {354 // Record stack before it gets lost in the promise chain.355 const stack = getStack();356 const intermediate = promise.then(value => {357 throw new AssertionError({358 assertion: 'throwsAsync',359 message,360 stack,361 values: [formatWithLabel(`${wasReturned ? 'Returned promise' : 'Promise'} resolved with:`, value)]362 });363 }, reason => {364 assertExpectations({365 assertion: 'throwsAsync',366 actual: reason,367 expectations,368 message,369 prefix: `${wasReturned ? 'Returned promise' : 'Promise'} rejected with`,370 stack371 });372 return reason;373 });374 pending(this, intermediate);375 // Don't reject the returned promise, even if the assertion fails.376 return intermediate.catch(noop);377 };378 if (isPromise(thrower)) {379 return handlePromise(thrower, false);380 }381 let retval;382 let actual;383 let threw = false;384 try {385 retval = thrower();386 } catch (error) {387 actual = error;388 threw = true;389 }390 if (threw) {391 fail(this, new AssertionError({392 assertion: 'throwsAsync',393 message,394 values: [formatWithLabel('Function threw synchronously. Use `t.throws()` instead:', actual)]395 }));396 return Promise.resolve();397 }398 if (isPromise(retval)) {399 return handlePromise(retval, true);400 }401 fail(this, new AssertionError({402 assertion: 'throwsAsync',403 message,404 values: [formatWithLabel('Function returned:', retval)]405 }));406 return Promise.resolve();407 },408 notThrows(fn, message) {409 if (typeof fn !== 'function') {410 fail(this, new AssertionError({411 assertion: 'notThrows',412 improperUsage: true,413 message: '`t.notThrows()` must be called with a function',414 values: [formatWithLabel('Called with:', fn)]415 }));416 return;417 }418 try {419 fn();420 } catch (error) {421 fail(this, new AssertionError({422 assertion: 'notThrows',423 message,424 values: [formatWithLabel('Function threw:', error)]425 }));426 return;427 }428 pass(this);429 },430 notThrowsAsync(nonThrower, message) {431 if (typeof nonThrower !== 'function' && !isPromise(nonThrower)) {432 fail(this, new AssertionError({433 assertion: 'notThrowsAsync',434 improperUsage: true,435 message: '`t.notThrowsAsync()` must be called with a function or promise',436 values: [formatWithLabel('Called with:', nonThrower)]437 }));438 return Promise.resolve();439 }440 const handlePromise = (promise, wasReturned) => {441 // Record stack before it gets lost in the promise chain.442 const stack = getStack();443 const intermediate = promise.then(noop, reason => {444 throw new AssertionError({445 assertion: 'notThrowsAsync',446 message,447 stack,448 values: [formatWithLabel(`${wasReturned ? 'Returned promise' : 'Promise'} rejected with:`, reason)]449 });450 });451 pending(this, intermediate);452 // Don't reject the returned promise, even if the assertion fails.453 return intermediate.catch(noop);454 };455 if (isPromise(nonThrower)) {456 return handlePromise(nonThrower, false);457 }458 let retval;459 try {460 retval = nonThrower();461 } catch (error) {462 fail(this, new AssertionError({463 assertion: 'notThrowsAsync',464 message,465 values: [formatWithLabel('Function threw:', error)]466 }));467 return Promise.resolve();468 }469 if (!isPromise(retval)) {470 fail(this, new AssertionError({471 assertion: 'notThrowsAsync',472 message,473 values: [formatWithLabel('Function did not return a promise. Use `t.notThrows()` instead:', retval)]474 }));475 return Promise.resolve();476 }477 return handlePromise(retval, true);478 },479 snapshot(expected, optionsOrMessage, message) {480 const options = {};481 if (typeof optionsOrMessage === 'string') {482 message = optionsOrMessage;483 } else if (optionsOrMessage) {484 options.id = optionsOrMessage.id;485 }486 options.expected = expected;487 options.message = message;488 let result;489 try {490 result = this.compareWithSnapshot(options);491 } catch (error) {492 if (!(error instanceof snapshotManager.SnapshotError)) {493 throw error;494 }495 const improperUsage = {name: error.name, snapPath: error.snapPath};496 if (error instanceof snapshotManager.VersionMismatchError) {497 improperUsage.snapVersion = error.snapVersion;498 improperUsage.expectedVersion = error.expectedVersion;499 }500 fail(this, new AssertionError({501 assertion: 'snapshot',502 message: message || 'Could not compare snapshot',503 improperUsage504 }));505 return;506 }507 if (result.pass) {508 pass(this);509 } else if (result.actual) {510 fail(this, new AssertionError({511 assertion: 'snapshot',512 message: message || 'Did not match snapshot',513 values: [formatDescriptorDiff(result.actual, result.expected, {invert: true})]514 }));515 } else {516 fail(this, new AssertionError({517 assertion: 'snapshot',518 message: message || 'No snapshot available, run with --update-snapshots'519 }));520 }521 }522 };523 const enhancedAssertions = enhanceAssert(pass, fail, {524 truthy(actual, message) {525 if (!actual) {526 throw new AssertionError({527 assertion: 'truthy',528 message,529 operator: '!!',530 values: [formatWithLabel('Value is not truthy:', actual)]531 });532 }533 },534 falsy(actual, message) {535 if (actual) {536 throw new AssertionError({537 assertion: 'falsy',538 message,539 operator: '!',540 values: [formatWithLabel('Value is not falsy:', actual)]541 });542 }543 },544 true(actual, message) {545 if (actual !== true) {546 throw new AssertionError({547 assertion: 'true',548 message,549 values: [formatWithLabel('Value is not `true`:', actual)]550 });551 }552 },553 false(actual, message) {554 if (actual !== false) {555 throw new AssertionError({556 assertion: 'false',557 message,558 values: [formatWithLabel('Value is not `false`:', actual)]559 });560 }561 },562 regex(string, regex, message) {563 if (typeof string !== 'string') {564 throw new AssertionError({565 assertion: 'regex',566 improperUsage: true,567 message: '`t.regex()` must be called with a string',568 values: [formatWithLabel('Called with:', string)]569 });570 }571 if (!(regex instanceof RegExp)) {572 throw new AssertionError({573 assertion: 'regex',574 improperUsage: true,575 message: '`t.regex()` must be called with a regular expression',576 values: [formatWithLabel('Called with:', regex)]577 });578 }579 if (!regex.test(string)) {580 throw new AssertionError({581 assertion: 'regex',582 message,583 values: [584 formatWithLabel('Value must match expression:', string),585 formatWithLabel('Regular expression:', regex)586 ]587 });588 }589 },590 notRegex(string, regex, message) {591 if (typeof string !== 'string') {592 throw new AssertionError({593 assertion: 'notRegex',594 improperUsage: true,595 message: '`t.notRegex()` must be called with a string',596 values: [formatWithLabel('Called with:', string)]597 });598 }599 if (!(regex instanceof RegExp)) {600 throw new AssertionError({601 assertion: 'notRegex',602 improperUsage: true,603 message: '`t.notRegex()` must be called with a regular expression',604 values: [formatWithLabel('Called with:', regex)]605 });606 }607 if (regex.test(string)) {608 throw new AssertionError({609 assertion: 'notRegex',610 message,611 values: [612 formatWithLabel('Value must not match expression:', string),613 formatWithLabel('Regular expression:', regex)614 ]615 });616 }617 }618 });619 return Object.assign(assertions, enhancedAssertions);620}...
Using AI Code Generation
1var IntlPolyfill = require('intl');2var en = require('intl/locale-data/jsonp/en.js');3var fr = require('intl/locale-data/jsonp/fr.js');4var locales = ['en', 'fr'];5var localeData = {6};7locales.forEach(function (locale) {8 if (IntlPolyfill.__disableRegExpRestore) {9 IntlPolyfill.__disableRegExpRestore();10 }11 Intl.NumberFormat = IntlPolyfill.NumberFormat;12 Intl.NumberFormat.__addLocaleData(localeData[locale]);13});14var test = new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' });15console.log(test.formatWithLabel(123456.789, 'USD'));16### `IntlPolyfill.__addLocaleData(localeData)`17var IntlPolyfill = require('intl');18var en = require('intl/locale-data/jsonp/en.js');19var fr = require('intl/locale-data/jsonp/fr.js');20var locales = ['en', 'fr'];21var localeData = {22};23locales.forEach(function (locale) {24 if (IntlPolyfill.__disableRegExpRestore) {25 IntlPolyfill.__disableRegExpRestore();26 }27 Intl.NumberFormat = IntlPolyfill.NumberFormat;28 Intl.NumberFormat.__addLocaleData(localeData[locale]);29});30var test = new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' });31console.log(test.formatWithLabel(123456.789, 'USD'));32### `Intl.DateTimeFormat.supportedLocalesOf(locales[, options])`33var IntlPolyfill = require('intl');34var en = require('intl/locale-data/jsonp
Using AI Code Generation
1var dateFormat = require('dateformat');2console.log(dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT"));3var dateFormat = require('dateformat');4dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';5console.log(dateFormat(new Date(), "hammerTime"));6var dateFormat = require('dateformat');7dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';8console.log(dateFormat(new Date(), "hammerTime"));9var dateFormat = require('dateformat');10console.log(dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT Z"));
Using AI Code Generation
1const availableFormats = require('available-formats');2const formatWithLabel = availableFormats.formatWithLabel;3const format = availableFormats.format;4const date = new Date();5const options = {6};7const formattedDate = formatWithLabel('en-US', date, options);8console.log(formattedDate);9const availableFormats = require('available-formats');10const formatWithLabel = availableFormats.formatWithLabel;11const format = availableFormats.format;12const date = new Date();13const options = {14};15const formattedDate = format('en-US', date, options);16console.log(formattedDate);
Using AI Code Generation
1var stringFormatter = require('string-formatter');2var str = 'Hello {0} {1} {0}';3console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));4var stringFormatter = require('string-formatter');5var str = 'Hello {0} {1} {0}';6console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));7var stringFormatter = require('string-formatter');8var str = 'Hello {0} {1} {0}';9console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));10var stringFormatter = require('string-formatter');11var str = 'Hello {0} {1} {0}';12console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));13var stringFormatter = require('string-formatter');14var str = 'Hello {0} {1} {0}';15console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));16var stringFormatter = require('string-formatter');17var str = 'Hello {0} {1} {0}';18console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));19var stringFormatter = require('string-formatter');20var str = 'Hello {0} {1} {0}';21console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));22var stringFormatter = require('string-formatter');23var str = 'Hello {0} {1} {0}';24console.log(stringFormatter.formatWithLabel(str, {0: 'World', 1: '!!!'}));25var stringFormatter = require('string-formatter');26var str = 'Hello {0} {1} {0}';
Using AI Code Generation
1var availableLocales = ["en-US", "en-GB", "de-DE"];2var label = "Country";3var value = "Germany";4var result = formatWithLabel(availableLocales, label, value);5console.log(result);6var supportedLocales = ["en", "de"];7var label = "Country";8var value = "Germany";9var result = formatWithLabel(supportedLocales, label, value);10console.log(result);11var availableLocales = ["en-US", "en-GB", "de-DE"];12var supportedLocales = ["en", "de"];13var label = "Country";14var value = "Germany";15var result = formatWithLabel(availableLocales, supportedLocales, label, value);16console.log(result);17 var availableLocales = ["en-US", "en-GB", "de-DE"];18 var supportedLocales = ["en", "de"];19 var label = "Country";20 var value = "Germany";21 var result = formatWithLabel(availableLocales, supportedLocales
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!!