How to use formatErrorValue method in ava

Best JavaScript code snippet using ava

test.js

Source:test.js Github

copy

Full Screen

...8const plur = require('plur');9const assert = require('./assert');10const globals = require('./globals');11const concordanceOptions = require('./concordance-options').default;12function formatErrorValue(label, error) {13 const formatted = concordance.format(error, concordanceOptions);14 return {label, formatted};15}16class SkipApi {17 constructor(test) {18 this._test = test;19 }20}21const captureStack = start => {22 const limitBefore = Error.stackTraceLimit;23 Error.stackTraceLimit = 1;24 const obj = {};25 Error.captureStackTrace(obj, start);26 Error.stackTraceLimit = limitBefore;27 return obj.stack;28};29class ExecutionContext {30 constructor(test) {31 Object.defineProperties(this, {32 _test: {value: test},33 skip: {value: new SkipApi(test)}34 });35 }36 plan(ct) {37 this._test.plan(ct, captureStack(this.plan));38 }39 get end() {40 const end = this._test.bindEndCallback();41 const endFn = err => end(err, captureStack(endFn));42 return endFn;43 }44 get title() {45 return this._test.title;46 }47 get context() {48 const contextRef = this._test.contextRef;49 return contextRef && contextRef.context;50 }51 set context(context) {52 const contextRef = this._test.contextRef;53 if (!contextRef) {54 this._test.saveFirstError(new Error(`\`t.context\` is not available in ${this._test.metadata.type} tests`));55 return;56 }57 contextRef.context = context;58 }59 _throwsArgStart(assertion, file, line) {60 this._test.trackThrows({assertion, file, line});61 }62 _throwsArgEnd() {63 this._test.trackThrows(null);64 }65}66{67 const assertions = assert.wrapAssertions({68 log(executionContext, text) {69 executionContext._test.addLog(text);70 },71 pass(executionContext) {72 executionContext._test.countPassedAssertion();73 },74 pending(executionContext, promise) {75 executionContext._test.addPendingAssertion(promise);76 },77 fail(executionContext, error) {78 executionContext._test.addFailedAssertion(error);79 }80 });81 Object.assign(ExecutionContext.prototype, assertions);82 function skipFn() {83 this._test.countPassedAssertion();84 }85 Object.keys(assertions).forEach(el => {86 SkipApi.prototype[el] = skipFn;87 });88}89class Test {90 constructor(options) {91 this.contextRef = options.contextRef;92 this.failWithoutAssertions = options.failWithoutAssertions;93 this.fn = isGeneratorFn(options.fn) ? co.wrap(options.fn) : options.fn;94 this.metadata = options.metadata;95 this.onResult = options.onResult;96 this.title = options.title;97 this.logs = [];98 this.snapshotInvocationCount = 0;99 this.compareWithSnapshot = assertionOptions => {100 const belongsTo = assertionOptions.id || this.title;101 const expected = assertionOptions.expected;102 const index = assertionOptions.id ? 0 : this.snapshotInvocationCount++;103 const label = assertionOptions.id ? '' : assertionOptions.message || `Snapshot ${this.snapshotInvocationCount}`;104 return options.compareTestSnapshot({belongsTo, expected, index, label});105 };106 this.assertCount = 0;107 this.assertError = undefined;108 this.calledEnd = false;109 this.duration = null;110 this.endCallbackFinisher = null;111 this.finishDueToAttributedError = null;112 this.finishDueToInactivity = null;113 this.finishing = false;114 this.pendingAssertionCount = 0;115 this.pendingThrowsAssertion = null;116 this.planCount = null;117 this.startedAt = 0;118 }119 bindEndCallback() {120 if (this.metadata.callback) {121 return (err, stack) => {122 this.endCallback(err, stack);123 };124 }125 throw new Error('`t.end()`` is not supported in this context. To use `t.end()` as a callback, you must use "callback mode" via `test.cb(testName, fn)`');126 }127 endCallback(err, stack) {128 if (this.calledEnd) {129 this.saveFirstError(new Error('`t.end()` called more than once'));130 return;131 }132 this.calledEnd = true;133 if (err) {134 this.saveFirstError(new assert.AssertionError({135 actual: err,136 message: 'Callback called with an error',137 stack,138 values: [formatErrorValue('Callback called with an error:', err)]139 }));140 }141 if (this.endCallbackFinisher) {142 this.endCallbackFinisher();143 }144 }145 createExecutionContext() {146 return new ExecutionContext(this);147 }148 countPassedAssertion() {149 if (this.finishing) {150 this.saveFirstError(new Error('Assertion passed, but test has already finished'));151 }152 this.assertCount++;153 }154 addLog(text) {155 this.logs.push(text);156 }157 addPendingAssertion(promise) {158 if (this.finishing) {159 this.saveFirstError(new Error('Assertion passed, but test has already finished'));160 }161 this.assertCount++;162 this.pendingAssertionCount++;163 promise164 .catch(err => this.saveFirstError(err))165 .then(() => this.pendingAssertionCount--);166 }167 addFailedAssertion(error) {168 if (this.finishing) {169 this.saveFirstError(new Error('Assertion failed, but test has already finished'));170 }171 this.assertCount++;172 this.saveFirstError(error);173 }174 saveFirstError(err) {175 if (!this.assertError) {176 this.assertError = err;177 }178 }179 plan(count, planStack) {180 if (typeof count !== 'number') {181 throw new TypeError('Expected a number');182 }183 this.planCount = count;184 // In case the `planCount` doesn't match `assertCount, we need the stack of185 // this function to throw with a useful stack.186 this.planStack = planStack;187 }188 verifyPlan() {189 if (!this.assertError && this.planCount !== null && this.planCount !== this.assertCount) {190 this.saveFirstError(new assert.AssertionError({191 assertion: 'plan',192 message: `Planned for ${this.planCount} ${plur('assertion', this.planCount)}, but got ${this.assertCount}.`,193 operator: '===',194 stack: this.planStack195 }));196 }197 }198 verifyAssertions() {199 if (!this.assertError) {200 if (this.failWithoutAssertions && !this.calledEnd && this.planCount === null && this.assertCount === 0) {201 this.saveFirstError(new Error('Test finished without running any assertions'));202 } else if (this.pendingAssertionCount > 0) {203 this.saveFirstError(new Error('Test finished, but an assertion is still pending'));204 }205 }206 }207 trackThrows(pending) {208 this.pendingThrowsAssertion = pending;209 }210 detectImproperThrows(err) {211 if (!this.pendingThrowsAssertion) {212 return false;213 }214 const pending = this.pendingThrowsAssertion;215 this.pendingThrowsAssertion = null;216 const values = [];217 if (err) {218 values.push(formatErrorValue(`The following error was thrown, possibly before \`t.${pending.assertion}()\` could be called:`, err));219 }220 this.saveFirstError(new assert.AssertionError({221 assertion: pending.assertion,222 fixedSource: {file: pending.file, line: pending.line},223 improperUsage: true,224 message: `Improper usage of \`t.${pending.assertion}()\` detected`,225 stack: err instanceof Error && err.stack,226 values227 }));228 return true;229 }230 waitForPendingThrowsAssertion() {231 return new Promise(resolve => {232 this.finishDueToAttributedError = () => {233 resolve(this.finishPromised());234 };235 this.finishDueToInactivity = () => {236 this.detectImproperThrows();237 resolve(this.finishPromised());238 };239 // Wait up to a second to see if an error can be attributed to the240 // pending assertion.241 globals.setTimeout(() => this.finishDueToInactivity(), 1000).unref();242 });243 }244 attributeLeakedError(err) {245 if (!this.detectImproperThrows(err)) {246 return false;247 }248 this.finishDueToAttributedError();249 return true;250 }251 callFn() {252 try {253 return {254 ok: true,255 retval: this.fn(this.createExecutionContext())256 };257 } catch (err) {258 return {259 ok: false,260 error: err261 };262 }263 }264 run() {265 this.startedAt = globals.now();266 const result = this.callFn();267 if (!result.ok) {268 if (!this.detectImproperThrows(result.error)) {269 this.saveFirstError(new assert.AssertionError({270 message: 'Error thrown in test',271 stack: result.error instanceof Error && result.error.stack,272 values: [formatErrorValue('Error thrown in test:', result.error)]273 }));274 }275 return this.finish();276 }277 const returnedObservable = isObservable(result.retval);278 const returnedPromise = isPromise(result.retval);279 let promise;280 if (returnedObservable) {281 promise = observableToPromise(result.retval);282 } else if (returnedPromise) {283 // `retval` can be any thenable, so convert to a proper promise.284 promise = Promise.resolve(result.retval);285 }286 if (this.metadata.callback) {287 if (returnedObservable || returnedPromise) {288 const asyncType = returnedObservable ? 'observables' : 'promises';289 this.saveFirstError(new Error(`Do not return ${asyncType} from tests declared via \`test.cb(...)\`, if you want to return a promise simply declare the test via \`test(...)\``));290 return this.finish();291 }292 if (this.calledEnd) {293 return this.finish();294 }295 return new Promise(resolve => {296 this.endCallbackFinisher = () => {297 resolve(this.finishPromised());298 };299 this.finishDueToAttributedError = () => {300 resolve(this.finishPromised());301 };302 this.finishDueToInactivity = () => {303 this.saveFirstError(new Error('`t.end()` was never called'));304 resolve(this.finishPromised());305 };306 });307 }308 if (promise) {309 return new Promise(resolve => {310 this.finishDueToAttributedError = () => {311 resolve(this.finishPromised());312 };313 this.finishDueToInactivity = () => {314 const err = returnedObservable ?315 new Error('Observable returned by test never completed') :316 new Error('Promise returned by test never resolved');317 this.saveFirstError(err);318 resolve(this.finishPromised());319 };320 promise321 .catch(err => {322 if (!this.detectImproperThrows(err)) {323 this.saveFirstError(new assert.AssertionError({324 message: 'Rejected promise returned by test',325 stack: err instanceof Error && err.stack,326 values: [formatErrorValue('Rejected promise returned by test. Reason:', err)]327 }));328 }329 })330 .then(() => resolve(this.finishPromised()));331 });332 }333 return this.finish();334 }335 finish() {336 this.finishing = true;337 if (!this.assertError && this.pendingThrowsAssertion) {338 return this.waitForPendingThrowsAssertion();339 }340 this.verifyPlan();...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import {formatDate} from './date.filter';2import {formatErrorValue} from './error.filter';3export default {4 formatDate,5 formatErrorValue,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import test from 'ava';2import { formatErrorValue } from 'ava/lib/format-error';3test('my passing test', t => {4 t.pass();5});6test('my failing test', t => {7 t.fail();8});9test('my throwing test', t => {10 throw new Error('my error');11});12test('my rejected test', t => {13 return Promise.reject(new Error('my error'));14});15test('my async throwing test', async t => {16 throw new Error('my error');17});18test('my async rejected test', async t => {19 return Promise.reject(new Error('my error'));20});21test('my async failing test', async t => {22 t.fail();23});24test('my async passing test', async t => {25 t.pass();26});27test('my promise failing test', t => {28 return new Promise((resolve, reject) => {29 t.fail();30 });31});32test('my promise passing test', t => {33 return new Promise((resolve, reject) => {34 t.pass();35 });36});37test('my promise throwing test', t => {38 return new Promise((resolve, reject) => {39 throw new Error('my error');40 });41});42test('my promise rejected test', t => {43 return new Promise((resolve, reject) => {44 return Promise.reject(new Error('my error'));45 });46});47test('my promise async failing test', async t => {48 return new Promise((resolve, reject) => {49 t.fail();50 });51});52test('my promise async passing test', async t => {53 return new Promise((resolve, reject) => {54 t.pass();55 });56});57test('my promise async throwing test', async t => {58 return new Promise((resolve, reject) => {59 throw new Error('my error');60 });61});62test('my promise async rejected test', async t => {63 return new Promise((resolve, reject) => {64 return Promise.reject(new Error('my error'));65 });66});67test('my promise async failing test', async t => {68 return new Promise((resolve, reject) => {69 t.fail();70 });71});72test('my promise async passing test', async t => {73 return new Promise((resolve, reject) => {74 t.pass();75 });76});77test('my promise async throwing test', async t => {78 return new Promise((resolve, reject) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import test from 'ava';2import formatErrorValue from 'ava/lib/format-error-value';3test('foo', t => {4 t.is(formatErrorValue('foo'), 'foo');5});6test('bar', t => {7 t.is(formatErrorValue('bar'), 'bar');8});9test('baz', t => {10 t.is(formatErrorValue('baz'), 'baz');11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import test from 'ava';2import {formatErrorValue} from 'ava/lib/format-error';3test('test1', t => {4 const error = new Error('test error');5 const result = formatErrorValue(error);6 console.log(result);7 t.pass();8});9import test from 'ava';10import {formatErrorValue} from 'ava/lib/format-error';11test('test2', t => {12 const error = new Error('test error');13 const result = formatErrorValue(error);14 console.log(result);15 t.pass();16});17import test from 'ava';18import {formatErrorValue} from 'ava/lib/format-error';19test('test3', t => {20 const error = new Error('test error');21 const result = formatErrorValue(error);22 console.log(result);23 t.pass();24});25import test from 'ava';26import {formatErrorValue} from 'ava/lib/format-error';27test('test4', t => {28 const error = new Error('test error');29 const result = formatErrorValue(error);30 console.log(result);31 t.pass();32});33import test from 'ava';34import {formatErrorValue} from 'ava/lib/format-error';35test('test5', t => {36 const error = new Error('test error');37 const result = formatErrorValue(error);38 console.log(result);39 t.pass();40});41import test from 'ava';42import {formatErrorValue} from 'ava/lib/format-error';43test('test6', t => {44 const error = new Error('test error');45 const result = formatErrorValue(error);46 console.log(result);47 t.pass();48});49import test from 'ava';50import {formatErrorValue} from 'ava/lib/format-error';51test('test7', t => {52 const error = new Error('test error');53 const result = formatErrorValue(error);54 console.log(result);

Full Screen

Using AI Code Generation

copy

Full Screen

1const test = require('ava');2const {formatErrorValue} = require('ava/lib/format-error');3const {format} = require('util');4test('formatErrorValue', t => {5 const error = new Error('foo');6 error.actual = {foo: 'bar'};7 error.expected = {foo: 'baz'};8 error.operator = 'test';9 const formatted = formatErrorValue(error);10 t.is(formatted, format(`%o11%o`, error.actual, error.operator, error.expected));12});13const test = require('ava');14const {formatErrorValue} = require('ava/lib/format-error');15const {format} = require('util');16test('formatErrorValue', t => {17 const error = new Error('foo');18 error.actual = {foo: 'bar'};19 error.expected = {foo: 'baz'};20 error.operator = 'test';21 const formatted = formatErrorValue(error);22 t.is(formatted, format(`%o23%o`, error.actual, error.operator, error.expected));24});25const test = require('ava');26const {formatErrorValue} = require('ava/lib/format-error');27const {format} = require('util');28test('formatErrorValue', t => {29 const error = new Error('foo');30 error.actual = {foo: 'bar'};31 error.expected = {foo: 'baz'};32 error.operator = 'test';33 const formatted = formatErrorValue(error);34 t.is(formatted, format(`%o35%o`, error.actual, error.operator, error.expected));36});37const test = require('ava');38const {formatErrorValue} = require('ava/lib/format-error');39const {format} = require('util');40test('formatErrorValue', t => {41 const error = new Error('foo');42 error.actual = {foo: 'bar'};43 error.expected = {foo: 'baz'};44 error.operator = 'test';45 const formatted = formatErrorValue(error);46 t.is(formatted, format(`%o47%o`, error.actual, error.operator, error.expected));48});49const test = require('ava');50const {format

Full Screen

Using AI Code Generation

copy

Full Screen

1import test from 'ava'2import {formatErrorValue} from 'ava/lib/assert'3test('test formatErrorValue', t => {4 const value = {5 }6 console.log(formatErrorValue(value))7})8import test from 'ava'9import {formatErrorValue} from 'ava/lib/assert'10test('test formatErrorValue', t => {11 const value = {12 }13 console.log(formatErrorValue(value))14})15import test from 'ava'16import {formatErrorValue} from 'ava/lib/assert'17test('test formatErrorValue', t => {18 const value = {19 }20 console.log(formatErrorValue(value))21})22import test from 'ava'23import {formatErrorValue} from 'ava/lib/assert'24test('test formatErrorValue', t => {25 const value = {26 }27 console.log(formatErrorValue(value))28})29import test from 'ava'30import {formatErrorValue} from 'ava/lib/assert'31test('test formatErrorValue', t => {32 const value = {33 }34 console.log(formatErrorValue(value))35})

Full Screen

Using AI Code Generation

copy

Full Screen

1const {formatErrorValue} = require('ava/lib/format-assert-error');2test('test', t => {3 t.throws(() => {4 throw new Error('test');5 }, {6 message: formatErrorValue('test')7 });8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { formatErrorValue } = require('ava/lib/serialize-error');2const error = new Error('foo');3console.log(formatErrorValue(error));4const { formatErrorValue } = require('ava/lib/serialize-error');5const error = new Error('foo');6console.log(formatErrorValue(error));7const { formatErrorValue } = require('ava/lib/serialize-error');8const error = new Error('foo');9console.log(formatErrorValue(error));10const { formatErrorValue } = require('ava/lib/serialize-error');11const error = new Error('foo');12console.log(formatErrorValue(error));13const { formatErrorValue } = require('ava/lib/serialize-error');14const error = new Error('foo');15console.log(formatErrorValue(error));16const { formatErrorValue } = require('ava/lib/serialize-error');17const error = new Error('foo');18console.log(formatErrorValue(error));19const { formatErrorValue } = require('ava/lib/serialize-error');20const error = new Error('foo');21console.log(formatErrorValue(error));22const { formatErrorValue } = require('ava/lib/serialize-error');23const error = new Error('foo');24console.log(formatErrorValue(error));25const { formatErrorValue } = require('ava/lib/serialize-error');26const error = new Error('foo');27console.log(formatErrorValue(error));28const { formatErrorValue } = require('ava/lib/serialize-error');29const error = new Error('foo');30console.log(formatErrorValue(error));31const { formatErrorValue } = require('ava/lib/serialize-error');32const error = new Error('foo');33console.log(formatErrorValue(error));34const { formatErrorValue } = require('ava/lib/serialize-error');35const error = new Error('foo');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { formatErrorValue } = require('./lib');2const error = new Error('This is an error');3const formattedError = formatErrorValue(error);4console.log(formattedError);5{6 stack: 'Error: This is an error\n at Object.<anonymous> (/Users/saurabh/Desktop/Nodejs-Error-Handling/test.js:6:15)\n at Module._compile (internal/modules/cjs/loader.js:1063:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n at Module.load (internal/modules/cjs/loader.js:928:32)\n at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)\n at internal/main/run_main_module.js:17:47'7}

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ava automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful