Best JavaScript code snippet using cypress
test.js
Source:test.js
...38 ipc.emit(`pin-heartbeat`)39 })40 // instruct the child to pin the ready event41 await ipc.emit('pin-ready', ...ARGS)42 await Promise.delay(SLEEP)43 {44 let count = 145 ipc.on('heartbeat', function () {46 called[`on-heartbeat (${count++})`] = true47 })48 }49 {50 let count = 151 ipc.once('heartbeat', function () {52 called[`once-heartbeat (${count++})`] = true53 })54 }55 {56 let count = 157 ipc.prependOnceListener('heartbeat', function () {58 called[`prepend-once-heartbeat (${count++})`] = true59 })60 }61 await Promise.delay(SLEEP)62 ipc.emit(`${event}-heartbeat`)63 await Promise.delay(SLEEP)64 assert.deepEqual(called, want)65}66describe('ipc-event-emitter', function () {67 this.slow(SLOW)68 it('returns an instance of IPCEventEmitter and EventEmitter', function () {69 assertIsIpcEventEmitter(ipc, 'IPC(...)')70 })71 it('emits events without arguments', async function () {72 // register ready-listeners before the event has fired73 ipc.on('ready', function (...args) {74 assertIsIpcEventEmitter(this)75 called['registered before ready (1)'] = args76 })77 ipc.on('ready', function (...args) {78 called['registered before ready (2)'] = args79 })80 await Promise.delay(SLEEP)81 // instruct the child to emit the ready event82 await ipc.emit('emit-ready')83 await Promise.delay(SLEEP)84 // register ready-listeners after the event has fired85 ipc.on('ready', (...args) => {86 called['registered after ready (1)'] = args87 })88 ipc.on('ready', (...args) => {89 called['registered after ready (2)'] = args90 })91 await Promise.delay(SLEEP)92 // confirm no args were passed to the pre-ready listeners93 // confirm the post-ready listeners have not been called94 assert.deepEqual(called, {95 'registered before ready (1)': [],96 'registered before ready (2)': [],97 })98 })99 it('emits events with arguments', async function () {100 // register ready-listeners before the event has fired101 ipc.on('ready', function (...args) {102 called['registered before ready (1)'] = args103 })104 ipc.on('ready', function (...args) {105 called['registered before ready (2)'] = args106 })107 await Promise.delay(SLEEP)108 // instruct the child to emit the ready event109 await ipc.emit('emit-ready', ...ARGS)110 await Promise.delay(SLEEP)111 // register ready-listeners after the event has fired112 ipc.on('ready', (...args) => {113 called['registered after ready (1)'] = args114 })115 ipc.on('ready', (...args) => {116 called['registered after ready (2)'] = args117 })118 await Promise.delay(SLEEP)119 // confirm args were passed to the pre-ready listeners120 // confirm the post-ready listeners have not been called121 assert.deepEqual(called, {122 'registered before ready (1)': ARGS,123 'registered before ready (2)': ARGS,124 })125 })126 it('pins events without arguments', async function () {127 // register ready-listeners before the event has fired128 ipc.on('ready', function (...args) {129 called['registered before ready (1)'] = args130 })131 ipc.on('ready', function (...args) {132 called['registered before ready (2)'] = args133 })134 await Promise.delay(SLEEP)135 // instruct the child to pin the ready event136 await ipc.emit('pin-ready')137 await Promise.delay(SLEEP)138 // register ready-listeners after the event has fired139 ipc.on('ready', (...args) => {140 called['registered after ready (1)'] = args141 })142 ipc.on('ready', (...args) => {143 called['registered after ready (2)'] = args144 })145 await Promise.delay(SLEEP)146 // confirm no args were passed to the pre-ready listeners147 // confirm the post-ready listeners have been called148 assert.deepEqual(called, {149 'registered before ready (1)': [],150 'registered before ready (2)': [],151 'registered after ready (1)': [],152 'registered after ready (2)': [],153 })154 })155 it('pins events with arguments', async function () {156 // register ready-listeners before the event has fired157 ipc.on('ready', function (...args) {158 called['registered before ready (1)'] = args159 })160 ipc.on('ready', function (...args) {161 called['registered before ready (2)'] = args162 })163 await Promise.delay(SLEEP)164 // instruct the child to pin the ready event165 await ipc.emit('pin-ready', ...ARGS)166 await Promise.delay(SLEEP)167 // register ready-listeners after the event has fired168 ipc.on('ready', (...args) => {169 called['registered after ready (1)'] = args170 })171 ipc.on('ready', (...args) => {172 called['registered after ready (2)'] = args173 })174 await Promise.delay(SLEEP)175 // confirm args were passed to the pre-ready listeners176 // confirm the post-ready listeners have been called177 assert.deepEqual(called, {178 'registered before ready (1)': ARGS,179 'registered before ready (2)': ARGS,180 'registered after ready (1)': ARGS,181 'registered after ready (2)': ARGS,182 })183 })184 it('pin + emit handles `on` and `once` listeners correctly', function () {185 return assertOnceOK('emit', {186 'on-heartbeat (1)': true,187 'once-heartbeat (1)': true,188 'prepend-once-heartbeat (1)': true,189 'on-heartbeat (2)': true,190 })191 })192 it('pin + pin handles `on` and `once` listeners correctly', function () {193 return assertOnceOK('pin', {194 'on-heartbeat (1)': true,195 'once-heartbeat (1)': true,196 'prepend-once-heartbeat (1)': true,197 'on-heartbeat (2)': true,198 })199 })200 it('unpins events', async function () {201 this.slow(SLOW * 6)202 // register ready-listeners before the event has fired203 ipc.on('ready', function (...args) {204 called['registered before ready (1)'] = args205 })206 ipc.on('ready', function (...args) {207 called['registered before ready (2)'] = args208 })209 await Promise.delay(SLEEP)210 // instruct the child to pin the ready event211 await ipc.emit('pin-ready', ...ARGS)212 await Promise.delay(SLEEP)213 // register ready-listeners after the event has fired214 ipc.on('ready', (...args) => {215 called['registered after ready (1)'] = args216 })217 ipc.on('ready', (...args) => {218 called['registered after ready (2)'] = args219 })220 await Promise.delay(SLEEP)221 // instruct the child to unpin the ready event222 await ipc.emit('unpin-ready')223 await Promise.delay(SLEEP)224 // register ready-listeners after the event has been unpinned225 ipc.on('ready', (...args) => {226 called['registered after ready (3)'] = args227 })228 ipc.on('ready', (...args) => {229 called['registered after ready (4)'] = args230 })231 await Promise.delay(SLEEP)232 // confirm the post-ready listeners have not been called233 assert.deepEqual(called, {234 'registered before ready (1)': ARGS,235 'registered before ready (2)': ARGS,236 'registered after ready (1)': ARGS,237 'registered after ready (2)': ARGS,238 })239 await Promise.delay(SLEEP)240 // confirm the post-unpinned listeners still respond to the event241 ipc.emit('emit-ready', ...ARGS)242 await Promise.delay(SLEEP)243 assert.deepEqual(called, {244 'registered before ready (1)': ARGS,245 'registered before ready (2)': ARGS,246 'registered after ready (1)': ARGS,247 'registered after ready (2)': ARGS,248 'registered after ready (3)': ARGS,249 'registered after ready (4)': ARGS,250 })251 })...
timers.js
Source:timers.js
...23IN THE SOFTWARE.24*/25describe("timeout", function () {26 it("should do nothing if the promise fulfills quickly", function() {27 Promise.delay(1).timeout(200).then(function(){28 });29 });30 it("should do nothing if the promise rejects quickly", function() {31 var goodError = new Error("haha!");32 return Promise.delay(1)33 .then(function () {34 throw goodError;35 })36 .timeout(200)37 .then(undefined, function (error) {38 assert(error === goodError);39 });40 });41 it("should reject with a timeout error if the promise is too slow", function() {42 return Promise.delay(1)43 .timeout(10)44 .caught(Promise.TimeoutError, function(){45 })46 });47 it("should reject with a custom timeout error if the promise is too slow and msg was provided", function() {48 return Promise.delay(1)49 .timeout(10, "custom")50 .caught(Promise.TimeoutError, function(e){51 assert(/custom/i.test(e.message));52 });53 });54 it("should cancel the parent promise once the timeout expires", function() {55 var didNotExecute = true;56 var wasRejectedWithTimeout = false;57 var p = Promise.delay(22).then(function() {58 didNotExecute = false;59 })60 p.timeout(11).thenReturn(10).caught(Promise.TimeoutError, function(e) {61 wasRejectedWithTimeout = true;62 })63 return Promise.delay(33).then(function() {64 assert(didNotExecute, "parent promise was not cancelled");65 assert(wasRejectedWithTimeout, "promise was not rejected with timeout");66 })67 });68 it("should not cancel the parent promise if there are multiple consumers", function() {69 var derivedNotCancelled = false;70 var p = Promise.delay(22);71 var derived = p.then(function() {72 derivedNotCancelled = true;73 })74 p.timeout(11).thenReturn(10)75 return Promise.delay(33).then(function() {76 assert(derivedNotCancelled, "derived promise was cancelled")77 })78 })79 var globalsAreReflectedInGlobalObject = (function(window) {80 var fn = function(id){return clearTimeout(id);};81 var old = window.clearTimeout;82 window.clearTimeout = fn;83 var ret = clearTimeout === fn;84 window.clearTimeout = old;85 return ret;86 })(globalObject);87 if (globalsAreReflectedInGlobalObject) {88 describe("timer handle clearouts", function() {89 var fakeSetTimeout, fakeClearTimeout;90 var expectedHandleType;91 before(function() {92 fakeSetTimeout = globalObject.setTimeout;93 fakeClearTimeout = globalObject.clearTimeout;94 globalObject.setTimeout = globalObject.oldSetTimeout;95 globalObject.clearTimeout = globalObject.oldClearTimeout;96 expectedHandleType = typeof (globalObject.setTimeout(function(){}, 1));97 });98 after(function() {99 globalObject.setTimeout = fakeSetTimeout;100 globalObject.clearTimeout = fakeClearTimeout;101 });102 it("should clear timeouts with proper handle type when fulfilled", function() {103 var old = globalObject.clearTimeout;104 var handleType = "empty";105 globalObject.clearTimeout = function(handle) {106 handleType = typeof handle;107 globalObject.clearTimeout = old;108 };109 return Promise.delay(1).timeout(10000).then(function() {110 assert.strictEqual(expectedHandleType, handleType);111 });112 });113 it("should clear timeouts with proper handle type when rejected", function() {114 var old = globalObject.clearTimeout;115 var handleType = "empty";116 globalObject.clearTimeout = function(handle) {117 handleType = typeof handle;118 globalObject.clearTimeout = old;119 };120 return new Promise(function(_, reject) {121 setTimeout(reject, 10);122 }).timeout(10000).then(null, function() {123 assert.strictEqual(expectedHandleType, handleType);124 });125 });126 })127 }128});129describe("delay", function () {130 it("should not delay rejection", function() {131 var promise = Promise.reject(5).delay(1);132 promise.then(assert.fail, function(){});133 return Promise.delay(1).then(function () {134 assert(!promise.isPending());135 });136 });137 it("should delay after resolution", function () {138 var promise1 = Promise.delay(1, "what");139 var promise2 = promise1.delay(1);140 return promise2.then(function (value) {141 assert(value === "what");142 });143 });144 it("should resolve follower promise's value", function() {145 var resolveF;146 var f = new Promise(function() {147 resolveF = arguments[0];148 });149 var v = new Promise(function(f) {150 setTimeout(function() {151 f(3);152 }, 1);153 });154 resolveF(v);155 return Promise.delay(1, f).then(function(value) {156 assert.equal(value, 3);157 });158 });159 it("should reject with a custom error if an error was provided as a parameter", function() {160 var err = Error("Testing Errors")161 return Promise.delay(1)162 .timeout(10, err)163 .caught(function(e){164 assert(e === err);165 });166 });...
bluebird.js
Source:bluebird.js
...16});17describe('bluebird library', function() {18 it('simple coroutine', function() {19 var result = Promise.coroutine(function *() {20 yield Promise.delay(200);21 return 'done';22 })();23 assert.instanceOf(result, Promise);24 return assert.eventually.equal(result, 'done');25 });26 it('coroutine returns promise', function() {27 var result = Promise.coroutine(function *() {28 yield Promise.delay(200);29 return Promise.resolve('value');30 })();31 assert.instanceOf(result, Promise);32 return assert.eventually.equal(result, 'value');33 });34 it('coroutine returns result of yielding a promise', function() {35 var result = Promise.coroutine(function *() {36 yield Promise.delay(200);37 return (yield Promise.resolve('value'));38 })();39 assert.instanceOf(result, Promise);40 return assert.eventually.equal(result, 'value');41 });42 it('simple coroutine, multiple yields', function() {43 var result = Promise.coroutine(function *slowAdd(a, b) {44 yield Promise.delay(100);45 var x = yield Promise.resolve(a);46 yield Promise.delay(100);47 var y = yield Promise.resolve(b);48 yield Promise.delay(100);49 return a + b;50 })(2, 3);51 return assert.eventually.equal(result, 5);52 });53 it('coroutine returns promise', function(done) {54 var coroutine = Promise.coroutine(function *() {55 var results = [];56 yield Promise.delay(200);57 return Promise.resolve('val');58 });59 coroutine().then(function(result) {60 assert.equal(result, 'val');61 done();62 }).catch(function(err) {63 done(err);64 });65 });66 it('returns coroutine promise to mocha', function() {67 return Promise.coroutine(function *() {68 var results = [];69 yield Promise.delay(200);70 return Promise.resolve('val').then(function(result) {71 assert.equal(result, 'val');72 });73 })();74 });75 it('coroutine throws error', function() {76 var coroutine = Promise.coroutine(function *() {77 var results = [];78 yield Promise.delay(200);79 throw new Error('gen error');80 return Promise.resolve('val');81 });82 83 return coroutine()84 .then(function() { throw new Error('should have thrown'); })85 .catch(function() { /* swallow error */ });86 87 });88 it('coroutine yields inner coroutine with yield', function() {89 var result = Promise.coroutine(function *() {90 yield Promise.delay(200);91 return yield Promise.coroutine(function *() {92 return yield Promise.resolve('val');93 })();94 })();95 return assert.eventually.equal(result, 'val');96 });97 it('coroutine uses yield* to delegate to inner generator', function() {98 var result = Promise.coroutine(function *() {99 yield Promise.delay(200);100 function *delay3Times() {101 yield Promise.delay(100);102 yield Promise.delay(100);103 yield Promise.delay(100);104 }105 yield *delay3Times();106 return Promise.resolve('vals');107 })();108 return assert.eventually.equal(result, 'vals');109 });110 it('coroutine uses yield* to return value', function() {111 var result = Promise.coroutine(function *() {112 yield Promise.delay(200);113 function *delay3Times() {114 yield Promise.delay(100);115 yield Promise.delay(100);116 yield Promise.delay(100);117 return 123;118 }119 return yield *delay3Times();120 })();121 return assert.eventually.equal(result, 123);122 });123 it('coroutine uses yield* to return a yielded promise', function() {124 var result = Promise.coroutine(function *() {125 yield Promise.delay(200);126 function *delay3Times() {127 yield Promise.delay(100);128 yield Promise.delay(100);129 yield Promise.delay(100);130 return yield Promise.resolve(123);131 }132 return yield *delay3Times();133 })();134 return assert.eventually.equal(result, 123);135 });136 it('coroutine uses yield* to return a naked promise', function() {137 var result = Promise.coroutine(function *() {138 yield Promise.delay(200);139 function *delay3Times() {140 yield Promise.delay(100);141 yield Promise.delay(100);142 yield Promise.delay(100);143 return Promise.resolve(123);144 }145 return yield *delay3Times();146 })();147 return assert.eventually.equal(result, 123);148 });149 it('when returning non-yielded promise, coroutine fully resolves promise chain, returning value', function() {150 var result = Promise.coroutine(function *() {151 yield Promise.delay(200);152 function *delay3Times() {153 yield Promise.delay(100);154 yield Promise.delay(100);155 yield Promise.delay(100);156 return Promise.resolve(123);157 }158 return yield *delay3Times();159 })();160 return result.then(function(v) {161 return assert.equal(v, 123);162 });163 });164 describe('errors', function() {165 it('when yielded promise rejects with error, can be try/caught parent generator', function() {166 var result = Promise.coroutine(function *() {167 try {168 yield Promise.reject('promise error');169 } catch (e) {170 return yield Promise.resolve('error caught');171 }172 throw new Error('error not caught');173 })();174 return assert.eventually.equal(result, 'error caught');175 });176 it('when yielded promise rejects with error, parent coroutine rejectes', function() {177 var result = Promise.coroutine(function *() {178 yield Promise.reject('promise error');179 })();180 return assert.isRejected(result);181 });182 it('inner coroutine yields error', function() {183 var result = Promise.coroutine(function *() {184 yield Promise.coroutine(function *() {185 throw new Error('inner error');186 })();187 })();188 return assert.isRejected(result);189 });190 });191 describe('coroutines using objects', function() {192 function Foo() {193 this.fooValue = 'foo';194 }195 Foo.prototype.doFooAsync = function *() {196 yield Promise.delay(100);197 this.fooValue = 'doFooAsync';198 };199 Foo.prototype.doFooCoroutine = Promise.coroutine(function *() {200 yield Promise.delay(100);201 this.fooValue = 'doFooCoroutine';202 });203 it('can invoke object methods', function() {204 var foo = new Foo();205 var result = Promise.coroutine(foo.doFooAsync.bind(foo))();206 return result.then(function() {207 assert.equal(foo.fooValue, 'doFooAsync');208 });209 });210 it('can invoke object methods', function() {211 var foo = new Foo();212 return foo.doFooCoroutine().then(function() {213 assert.equal(foo.fooValue, 'doFooCoroutine');214 });...
kill.js
Source:kill.js
...9 it('can kill', async () => {10 let here1 = false, here2 = false, here3 = false11 async function job() {12 here1 = true13 await Promise.delay(100)14 here2 = true15 }16 const jobCoroutine = job();17 (async function() {18 try {19 const val = await jobCoroutine // eslint-disable-line no-unused-vars20 } catch (err) {21 here3 = true22 assert.isOk(isTerminatedError(err))23 }24 })()25 await Promise.delay(50)26 kill(jobCoroutine)27 await Promise.delay(150)28 assert.isOk(here1)29 assert.isNotOk(here2)30 assert.isOk(here3)31 timeApprox(200)32 })33 it('killing multiple times does nothing', async () => {34 let here1 = false, here2 = false, here3 = false35 async function job() {36 here1 = true37 await Promise.delay(100)38 here2 = true39 }40 const jobCoroutine = job();41 (async function() {42 try {43 const val = await jobCoroutine // eslint-disable-line no-unused-vars44 } catch (err) {45 here3 = true46 assert.isOk(isTerminatedError(err))47 }48 })()49 await Promise.delay(50)50 kill(jobCoroutine)51 kill(jobCoroutine)52 kill(jobCoroutine)53 kill(jobCoroutine)54 await Promise.delay(150)55 assert.isOk(here1)56 assert.isNotOk(here2)57 assert.isOk(here3)58 timeApprox(200)59 })60 it('children of killed coroutine are also killed', async () => {61 let here1 = false, here2 = false, here3 = false62 async function sideJob() {63 here1 = true64 await Promise.delay(100)65 here2 = true66 }67 let sideJobCoroutine68 async function job() {69 sideJobCoroutine = sideJob()70 }71 const jobCoroutine = job()72 await Promise.delay(50)73 kill(jobCoroutine)74 await Promise.delay(100)75 try {76 await sideJobCoroutine77 } catch (err) {78 here3 = true79 }80 assert.isOk(here1)81 assert.isNotOk(here2)82 assert.isOk(here3)83 })84 it('children of errored coroutine are also killed - explicit error', async () => {85 let here1 = false, here2 = false, here3 = false86 async function sideJob() {87 here1 = true88 await Promise.delay(100)89 here2 = true90 }91 async function job() {92 sideJob()93 await Promise.delay(50)94 throw new Error('whoops')95 }96 try {97 await job()98 } catch (err) {99 here3 = true100 }101 await Promise.delay(150)102 assert.isOk(here1)103 assert.isNotOk(here2)104 assert.isOk(here3)105 })106 it('children of errored coroutine are also killed - failed sibling job', async () => {107 let here1 = false, here2 = false, here3 = false108 async function sideJob() {109 here1 = true110 await Promise.delay(100)111 here2 = true112 }113 async function errorSideJob() {114 await Promise.delay(50)115 throw new Error('whooops')116 }117 async function job() {118 sideJob()119 errorSideJob()120 }121 try {122 await job()123 } catch (err) {124 here3 = true125 }126 await Promise.delay(150)127 assert.isOk(here1)128 assert.isNotOk(here2)129 assert.isOk(here3)130 })131 it('killing not awaited coroutine does not propagate error', async () => {132 let here1 = false, here2 = false133 async function job() {134 await Promise.delay(1000)135 }136 try {137 const jobCoroutine = job()138 kill(jobCoroutine)139 here1 = true140 } catch (err) {141 here2 = true142 }143 assert.isOk(here1)144 assert.isNotOk(here2)145 })146 it('can use argument to determine return value', async () => {147 async function job() {148 await Promise.delay(200)149 }150 const jobCoroutine = job()151 kill(jobCoroutine, 42)152 const res = await jobCoroutine153 assert.equal(res, 42)154 })155 it('killing succesfully terminated coroutine does nothing', async () => {156 async function job() {157 await Promise.delay(1)158 return 4159 }160 const jobCoroutine = job()161 await Promise.delay(20)162 kill(jobCoroutine)163 const res = await jobCoroutine164 assert.equal(res, 4)165 })166 it('killing errored coroutine does nothing', async () => {167 let here1 = false, here2 = false168 async function job() {169 await Promise.delay(1)170 throw new Error('whooops')171 }172 const jobCoroutine = job()173 try {174 await jobCoroutine175 } catch (err) {176 here1 = true177 }178 kill(jobCoroutine)179 try {180 await jobCoroutine181 } catch (err) {182 assert.equal(err.message, 'whooops')183 here2 = true184 }185 assert.isOk(here1)186 assert.isOk(here2)187 })188 it('invokes onKill handler', async () => {189 let here = false190 async function job() {191 await Promise.delay(100)192 }193 const jobCoroutine = job()194 jobCoroutine.onKill(() => {here = true})195 kill(jobCoroutine)196 assert.isOk(here)197 })198 it('kill validates its first argument', async () => {199 let here = false200 try {201 kill(Promise.delay(10))202 } catch (err) {203 assert.equal(err.type, assertCorType)204 here = true205 }206 assert.isOk(here)207 })208 it('killed coroutine acts as a failed promise', async () => {209 let here = false210 async function job() {211 await Promise.delay(10000)212 }213 const jobCor = job()214 kill(jobCor)215 await Promise.delay(10)216 jobCor.catch((err) => {217 isTerminatedError(err)218 here = true219 })220 await Promise.delay(10)221 assert.isOk(here)222 })...
error-test.js
Source:error-test.js
...12 else return d; 13 }))14 .on('error',e => err = e)15 .pipe(streamz(d => max = d));16 return Promise.delay(1000)17 .then(() => {18 t.same(err,'EXCEPTION','emits error');19 t.same(max,4,'stops');20 });21 });22 t.test('as error callback',t => {23 let max,err;24 valueStream()25 .pipe(streamz((d,cb) => {26 if (d == 5) cb('EXCEPTION');27 else cb(null,d);28 }))29 .on('error',e => err = e)30 .pipe(streamz(d => max = d));31 return Promise.delay(1000)32 .then(() => {33 t.same(err,'EXCEPTION','emits error');34 t.same(max,4,'stops');35 });36 });37 t.test('as promise rejection',t => {38 let max,err;39 valueStream()40 .pipe(streamz(d => {41 if (d == 5) return Promise.reject('EXCEPTION');42 else return Promise.resolve(d);43 }))44 .pipe(streamz(d => max = d))45 .promise()46 .catch(e => err = e);47 48 return Promise.delay(1000)49 .then(() => {50 t.same(err,'EXCEPTION','emits');51 t.same(max,4,'stops');52 });53 });54 t.test('as an async rejection',t => {55 let max,err;56 valueStream()57 .pipe(streamz(async function(d) {58 if (d == 5) await Promise.delay(100).then(() => Promise.reject('EXCEPTION'));59 else return Promise.resolve(d);60 }))61 .pipe(streamz(d => max = d))62 .promise()63 .catch(e => err = e);64 65 return Promise.delay(1000)66 .then(() => {67 t.same(err,'EXCEPTION','emits');68 t.same(max,4,'stops');69 });70 });71 t.test('as an async rejection',t => {72 let max,err;73 valueStream()74 .pipe(streamz(async function(d) {75 if (d == 5) await Promise.delay(100).then(() => Promise.reject('EXCEPTION'));76 else return Promise.resolve(d);77 }))78 .pipe(streamz(d => max = d))79 .promise()80 .catch(e => err = e);81 82 return Promise.delay(1000)83 .then(() => {84 t.same(err,'EXCEPTION','emits');85 t.same(max,4,'stops');86 });87 });88 t.test('error in component above',t => {89 return fs.createReadStream('this_file_does_not_exists')90 .pipe(streamz())91 .promise()92 .then(93 () => {throw 'Should Error';},94 e => t.same(e.code,'ENOENT','is captured')95 );96 });97 t.test('error without any child pipes', t => {98 try {99 streamz().emit('error','this is an error');100 }101 catch(e) {102 t.equal(e,'this is an error','throws');103 t.end();104 }105 });106});107t.test('catch', {autoend:true, jobs: 10}, t => {108 t.test('exception passes the error',t => {109 let max,err;110 valueStream()111 .pipe(streamz(d => {112 if (d == 5) throw 'EXCEPTION';113 else return d; 114 },{catch: e => {115 throw `Found: ${e}`;116 }}))117 .on('error',e => err = e)118 .pipe(streamz(d => max = d));119 return Promise.delay(1000)120 .then(() => {121 t.same(err,'Found: EXCEPTION','emits error');122 t.same(max,4,'stops');123 });124 });125 t.test('error callback',t => {126 let max,err;127 valueStream()128 .pipe(streamz((d,cb) => {129 if (d == 5) cb('EXCEPTION');130 else cb(null,d);131 },{catch: e => {132 throw `Found: ${e}`;133 }}))134 .on('error',e => err = e)135 .pipe(streamz(d => max = d));136 return Promise.delay(1000)137 .then(() => {138 t.same(err,'Found: EXCEPTION','emits error');139 t.same(max,4,'stops');140 });141 });142 t.test('as promise rejection',t => {143 let max,err;144 valueStream()145 .pipe(streamz(d => {146 if (d == 5) return Promise.reject('EXCEPTION');147 else return Promise.resolve(d);148 },{catch: e => {149 throw `Found: ${e}`;150 }}))151 .pipe(streamz(d => max = d))152 .promise()153 .catch(e => err = e);154 155 return Promise.delay(1000)156 .then(() => {157 t.same(err,'Found: EXCEPTION','emits');158 t.same(max,4,'stops');159 });160 });161 t.test('as async rejection',t => {162 let max,err;163 valueStream()164 .pipe(streamz(async function(d) {165 if (d == 5) await Promise.delay(100).then(() => { throw 'EXCEPTION';});166 else return Promise.resolve(d);167 },{catch: e => {168 throw `Found: ${e}`;169 }}))170 .pipe(streamz(d => max = d))171 .promise()172 .catch(e => err = e);173 174 return Promise.delay(1000)175 .then(() => {176 t.same(err,'Found: EXCEPTION','emits');177 t.same(max,4,'stops');178 });179 });180 t.test('ignoring the error',t => {181 let max,err,caughtErr,caughtData;182 valueStream()183 .pipe(streamz(d => {184 if (d == 5) throw 'EXCEPTION';185 else return d; 186 },{catch: (e,d) => {187 caughtErr = e;188 caughtData = d;189 }}))190 .on('error',e => err = e)191 .pipe(streamz(d => max = d));192 return Promise.delay(1000)193 .then(() => {194 t.same(caughtErr,'EXCEPTION','The error is caught');195 t.same(caughtData,5);196 t.same(err,undefined,'Error is not emitted');197 t.same(max,9,'does not stop the stream');198 });199 });200 ...
example.js
Source:example.js
...3///////////////////////////////////////////////////////////////////////////////////4// services5var services = {6 redisOne: {7 start: function() { return Promise.delay(100); },8 stop: function() { return Promise.delay(100); }9 },10 redisTwo: {11 start: function() { return Promise.delay(100); },12 stop: function() { return Promise.delay(100); }13 },14 serverOne: {15 start: function() { return Promise.delay(100); },16 stop: function() { return Promise.delay(100); }17 },18 serverTwo: {19 start: function() { return Promise.delay(100); },20 stop: function() { return Promise.delay(100); }21 },22 serverThree: {23 start: function() { return Promise.delay(100); },24 stop: function() { return Promise.delay(100); }25 },26 elasticSearch: {27 start: function() { return Promise.delay(100); },28 stop: function() { return Promise.delay(100); }29 },30 mailAPI:{31 start: function() { return Promise.delay(100); },32 stop: function() { return Promise.delay(100); }33 },34 cache: {35 start: function() { return Promise.delay(100); },36 stop: function() { return Promise.delay(100); }37 },38 postgres: {39 start: function() { return Promise.delay(100); },40 stop: function() { return Promise.delay(100); }41 },42 loadBalancer: {43 start: function() { return Promise.delay(100); },44 stop: function() { return Promise.delay(100); }45 },46 workerOne: {47 start: function() { return Promise.delay(100); },48 stop: function() { return Promise.delay(100); }49 },50 workerTwo: {51 start: function() { return Promise.delay(100); },52 stop: function() { return Promise.delay(100); }53 }54}55///////////////////////////////////////////////////////////////////////////////////56// order57var dag = new Vorrang()58 .before('redisOne', 'cache')59 .before('redisTwo', 'cache')60 .before('cache', 'serverOne')61 .before('cache', 'serverTwo')62 .before('cache', 'serverThree')63 .before('postgres', 'serverOne')64 .before('postgres', 'serverTwo')65 .before('postgres', 'serverThree')66 .before('elasticSearch', 'serverOne')67 .before('elasticSearch', 'serverTwo')68 .before('elasticSearch', 'serverThree')69 .before('elasticSearch', 'workerOne')70 .before('elasticSearch', 'workerTwo')71 .before('postgres', 'workerOne')72 .before('postgres', 'workerTwo')73 .before('mailAPI', 'workerOne')74 .before('mailAPI', 'workerTwo')75 .before('serverOne', 'loadBalancer')76 .before('serverTwo', 'loadBalancer')77 .before('serverThree', 'loadBalancer')78 ;79///////////////////////////////////////////////////////////////////////////////////80// start & stop81var starting = [];82var running = [];83var stopping = [];84var stopped = [];85var start = function(names) {86 return Promise.all(names.map(function(name) {87 if (-1 !== starting.indexOf(name)) {88 return;89 }90 if (-1 !== running.indexOf(name)) {91 return;92 }93 console.log('starting: ' + name);94 var callback = services[name].start;95 var promise = Promise.resolve(callback());96 starting.push(name);97 return promise.then(function() {98 console.log('running: ' + name);99 running.push(name);100 return start(dag.whereAllParentsIn(running));101 });102 }));103};104var stop = function(names) {105 return Promise.all(names.map(function(name) {106 if (-1 !== stopping.indexOf(name)) {107 return;108 }109 if (-1 !== stopped.indexOf(name)) {110 return;111 }112 console.log('stopping: ' + name);113 var callback = services[name].stop;114 var promise = Promise.resolve(callback());115 stopping.push(name);116 return promise.then(function() {117 console.log('stopped: ' + name);118 stopped.push(name);119 return stop(dag.whereAllChildrenIn(stopped));120 });121 }));122};123start(dag.parentless()).then(function() {124 // TODO assert that all are really running125 console.log('running: ALL');126 return Promise.delay(1000);127}).then(function() {128 return stop(dag.childless());129}).then(function() {130 console.log('stopped: ALL');...
workflow.js
Source:workflow.js
...5 this.service = service6 this.config = config7 this._registered = []8 logger.info('check balance...', { meta: 'green' })9 return Promise.delay(11000)10 .then(function (result) {11 let money = DI.container.get(DI.FILETYPES.SendMoney)12 return money.sendMoney()13 })14 .then(function () {15 let uia = DI.container.get(DI.FILETYPES.UIA)16 return uia.start()17 })18 .then(function wait () {19 logger.info('starting to register Dapp...', { meta: 'green' })20 return Promise.delay(100)21 })22 .then(() => {23 let registerDapp = DI.container.get(DI.FILETYPES.RegisterDapp)24 return registerDapp.register()25 })26 .then((registeredTrans) => {27 this._registered[registeredTrans.trs] = registeredTrans.name28 return registeredTrans.trs29 })30 .then((transactionId) => {31 return Promise.delay(1000)32 .then(() => {33 let serializeNewDapp = DI.container.get(DI.FILETYPES.SerializedNewDappId)34 let result = serializeNewDapp.serializeSync(transactionId, this._registered[transactionId])35 if (result === true) {36 logger.info(`wrote dappId to: ${result}`)37 }38 return transactionId39 })40 .then((transactionId) => {41 let deploy = DI.container.get(DI.FILETYPES.Deploy)42 return deploy.deploy(transactionId, this._registered[transactionId])43 })44 .then(function wait (result) {45 let ms = 1000046 logger.verbose(`wait for: ${ms}`)47 return Promise.delay(ms)48 })49 .then((result) => {50 logger.verbose('stopping asch-Server for restart', { meta: 'green.inverse' })51 return this.service.stop()52 })53 .then((result) => {54 logger.verbose('stopping asch-server', { meta: 'green.inverse' })55 return Promise.delay(5000)56 })57 .then(() => {58 logger.info('starting asch node', { meta: 'green.inverse' })59 return this.service.start()60 })61 .then(() => {62 // TODO: Check if blockchain is ready63 return Promise.delay(20000)64 })65 .then(() => {66 logger.info('blockchain started', { meta: 'blue.inverse' })67 let refuelDapp = DI.container.get(DI.FILETYPES.RefuelDapp)68 return refuelDapp.start(this._registered[transactionId])69 })70 .then(() => {71 return Promise.delay(8000)72 })73 })74 .catch(function errorOccured (error) {75 logger.verbose('error in worklflow.js occured')76 logger.error('ERROR OCCURED')77 throw error78 })79}...
base.js
Source:base.js
1import uuid from 'node-uuid'2export default function(path, array) {3 const delay = resolve => setTimeout(resolve, 150)4 return {5 getAll() {6 if (process.env.API_URL) {7 return Vue.$http.get(`${process.env.API_URL}/${path}`)8 } else {9 return new Promise(delay).then(() => array)10 }11 },12 getOne(id) {13 if (process.env.API_URL) {14 return Vue.$http.get(`${process.env.API_URL}/${path}/${id}`)15 } else {16 return new Promise(delay).then(() => {17 const items = array.filter(item => item.id == id)18 return items.length === 0 ? null : items[0]19 })20 }21 },22 post(data) {23 if (process.env.API_URL) {24 return Vue.$http.post(`${process.env.API_URL}/${path}`, data)25 } else {26 if (!data.id) data.id = uuid.v4()27 return new Promise(delay).then(() => array.push(data))28 }29 },30 put(data) {31 if (process.env.API_URL) {32 return Vue.$http.put(`${process.env.API_URL}/${path}`, data)33 } else {34 return new Promise(delay).then(() => {35 const index = array.findIndex(item => item.id === data.id)36 array.splice(index, 1)37 array.push(data)38 })39 }40 },41 delete(id) {42 if (process.env.API_URL) {43 return Vue.$http.delete(`${process.env.API_URL}/${path}/${id}`)44 } else {45 return new Promise(delay).then(() => {46 const index = array.findIndex(item => item.id === id)47 array.splice(index, 1)48 })49 }50 }51 }...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe('Test', () => {2 it('test', () => {3 cy.get('.gLFyf').type('Hello World')4 cy.get('.gNO89b').click()5 cy.wait(5000)6 cy.get('.LC20lb').click()7 cy.wait(5000)8 })9})10describe('Test', () => {11 it('test', () => {12 cy.get('.gLFyf').type('Hello World')13 cy.get('.gNO89b').click()14 cy.wrap(Cypress.Promise.delay(5000))15 cy.get('.LC20lb').click()16 cy.wrap(Cypress.Promise.delay(5000))17 })18})19describe('Test', () => {20 it('test', () => {21 cy.get('.gLFyf').type('Hello World')22 cy.get('.gNO89b').click()23 cy.wait(5000)24 cy.get('.LC20lb').click()25 cy.wait(5000)26 })27})28describe('Test', () => {29 it('test', () => {30 cy.get('.gLFyf').type('Hello World')31 cy.get('.gNO89b').click()32 cy.wait(5000)33 cy.get('.LC20lb').click()34 cy.wait(5000)35 })36})37describe('Test', () => {38 it('test', () => {39 cy.get('.gLFyf').type('Hello World')40 cy.get('.gNO89b').click()41 cy.wait(5000)42 cy.get('.LC20lb').click()43 cy.wait(5000)44 })45})46describe('Test', () => {47 it('test', () => {48 cy.get('.gLFyf').type('Hello World')49 cy.get('.gNO89b').click()50 cy.wait(500
Using AI Code Generation
1describe('Promise.delay', function() {2 it('should delay', function() {3 cy.wait(3000)4 cy.get('input[name="q"]').type('Cypress')5 cy.wait(3000)6 cy.get('input[name="btnK"]').click()7 cy.wait(3000)8 })9})10describe('Promise.delay', function() {11 it('should delay', function() {12 cy.wait(3000)13 cy.get('input[name="q"]').type('Cypress')14 cy.wait(3000)15 cy.get('input[name="btnK"]').click()16 cy.wait(3000)17 })18})19describe('Promise.delay', function() {20 it('should delay', function() {21 cy.wait(3000)22 cy.get('input[name="q"]').type('Cypress')23 cy.wait(3000)24 cy.get('input[name="btnK"]').click()25 cy.wait(3000)26 })27})28describe('Promise.delay', function() {29 it('should delay', function() {30 cy.wait(3000)31 cy.get('input[name="q"]').type('Cypress')32 cy.wait(3000)33 cy.get('input[name="btnK"]').click()34 cy.wait(3000)35 })36})37describe('Promise.delay', function() {38 it('should delay', function() {39 cy.wait(3000)40 cy.get('input[name="q"]').type('Cypress')41 cy.wait(3000)42 cy.get('input[name="btnK"]').click()43 cy.wait(3000)44 })45})46describe('Promise.delay', function() {47 it('should delay', function() {48 cy.wait(3000)
Using AI Code Generation
1const delay = require('cypress-promise').delay2it('should wait for 5 seconds', () => {3 cy.get('#lst-ib').type('Cypress')4 delay(5000).then(() => {5 cy.get('#lst-ib').clear()6 })7})
Using AI Code Generation
1describe('Promise.delay', function() {2 it('should delay', function() {3 cy.get('button').click()4 cy.get('h1').should('contain', '1')5 cy.get('h1').should('contain', '2')6 cy.get('h1').should('contain', '3')7 cy.get('h1').should('contain', '4')8 cy.get('h1').should('contain', '5')9 })10})11Cypress.Commands.add('delay', (delay) => {12 return new Cypress.Promise((resolve) => {13 setTimeout(resolve, delay)14 })15})16describe('Promise.delay', function() {17 it('should delay', function() {18 cy.get('button').click()19 cy.get('h1').should('contain', '1')20 cy.delay(1000).then(() => {21 cy.get('h1').should('contain', '2')22 })23 cy.delay(1000).then(() => {24 cy.get('h1').should('contain', '3')25 })26 cy.delay(1000).then(() => {27 cy.get('h1').should('contain', '4')28 })29 cy.delay(1000).then(() => {30 cy.get('h1').should('contain', '5')31 })32 })33})34describe('Promise.delay', function() {35 it('should delay', function() {36 cy.get('button').click()37 cy.get('h1').should('contain', '1')38 cy.get('h1').should('contain', '2')39 cy.get('h1').should('contain', '3')40 cy.get('h1').should('contain', '4')41 cy.get('h1').should('contain', '5')42 })43})44Cypress.Commands.add('delay', (delay
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!