Best JavaScript code snippet using cypress
query-idb-test.js
Source:query-idb-test.js
...49 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {50 db.createObjectStore("TestModel");51 }});52 assert.isFalse(db.isReady);53 await db.whenReady();54 assert.isTrue(db.isReady);55 });56 test("whenIdle", async ()=>{57 /**58 * Return a promise that is resolved when the DB is ready and has commited all outstanding59 * updates.60 **/61 api.protoMethod();62 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {63 db.createObjectStore("TestModel");64 }});65 await db.whenReady();66 assert.isTrue(db.isIdle);67 db.put('TestModel', {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});68 assert.isTrue(db.isReady);69 assert.isFalse(db.isIdle);70 await db.whenIdle();71 assert.isTrue(db.isIdle);72 });73 test("properties", ()=>{74 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {75 db.createObjectStore("TestModel");76 }});77 api.protoProperty('isReady', {intro() {78 /**79 * true if db has completed initializing and is not closed, otherwise false80 **/81 }});82 api.protoProperty('isIdle', {intro() {83 /**84 * true if db has completed initializing and is not closed and has no outstanding updates,85 * otherwise false86 **/87 }});88 assert.isFalse(db.isIdle);89 assert.isFalse(db.isReady);90 });91 test("constructor", async ()=>{92 /**93 * Open a indexedDB database94 *95 * @param {string} name the name of the database96 * @param {number} [version] expected version of database97 * @param {function} [upgrade] `function({db, oldVersion})`98 * where `db` is the `QueryIDB` instance and `oldVersion` is the99 * current version of the database100 **/101 const QueryIDB = api.class();102 let count = 0;103 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db, oldVersion}) {104 assert.same(oldVersion, 1);105 db.createObjectStore("TestModel");106 ++count;107 }});108 assert.same(count, 0);109 await v.db.whenReady();110 assert.same(v.db.name, 'foo');111 assert.same(count, 1);112 ++count;113 assert.same(count, 2);114 });115 test("promisify", async ()=>{116 /**117 * perform a database action returning a promise118 *119 * @param {function} body the returns an `IDBRequest`120 * @returns {Promise}121 **/122 api.protoMethod('promisify');123 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {124 db.createObjectStore("TestModel");125 }});126 await db.whenReady();127 //[128 const id = await db.promisify(129 ()=>db.transaction(['TestModel'], 'readwrite')130 .objectStore('TestModel').put({_id: "id1", name: "foo"})131 );132 assert.equals(id, "id1");133 //]134 });135 group("queueChange", ()=>{136 /**137 * Queue a model change to update indexedDB when the current138 * {#trans-queue} successfully completes. Changes to model139 * instances with stopGap$ symbol true are ignored.140 *141 **/142 beforeEach(()=>{143 api.protoMethod();144 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {145 db.createObjectStore("TestModel");146 }});147 });148 test("simulated add, update", async ()=>{149 session.state.incPending();150 after(()=>{session.state.pendingCount() == 1 && session.state.decPending()});151 await v.db.whenReady();152 //[153 {154 v.foo = v.idb._dbs.foo;155 assert.same(v.foo._version, 2);156 after(v.TestModel.onChange(v.db.queueChange.bind(v.db)));157 v.f1 = v.TestModel.create({_id: 'foo123', name: 'foo', age: 5, gender: 'm'});158 v.fIgnore = v.TestModel.createStopGap({159 _id: 'fooIgnore', name: 'foo ignore', age: 10, gender: 'f'});160 }161 await v.db.whenReady();162 {163 refute(v.foo._store.TestModel.docs.fooIgnore);164 const iDoc = v.foo._store.TestModel.docs.foo123;165 assert.equals(iDoc, {166 _id: 'foo123', name: 'foo', age: 5, gender: 'm', $sim: ['del', undefined]});167 v.f1.$update('age', 10);168 }169 await v.db.whenReady();170 {171 const iDoc = v.foo._store.TestModel.docs.foo123;172 assert.equals(iDoc, {173 _id: 'foo123', name: 'foo', age: 10, gender: 'm', $sim: ['del', undefined]});174 v.f1.$remove();175 }176 await v.db.whenReady();177 {178 const iDoc = v.foo._store.TestModel.docs.foo123;179 assert.equals(iDoc, undefined);180 }181 //]182 });183 test("simulated remove", async ()=>{184 session.state.incPending();185 after(_=> {session.state.decPending()});186 //[187 await v.db.whenReady(); {188 v.foo = v.idb._dbs.foo;189 assert.same(v.foo._version, 2);190 after(v.TestModel.onChange(v.db.queueChange.bind(v.db)).stop);191 Query.insertFromServer(v.TestModel, {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});192 v.f1 = v.TestModel.findById('foo123');193 }194 await v.db.whenReady(); {195 const iDoc = v.foo._store.TestModel.docs.foo123;196 assert.equals(iDoc, {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});197 v.f1.$remove();198 await v.db.whenReady();199 }200 await v.db.whenReady(); {201 const iDoc = v.foo._store.TestModel.docs.foo123;202 assert.equals(iDoc, {_id: 'foo123', $sim: [{203 _id: 'foo123', name: 'foo', age: 5, gender: 'm'}, undefined]});204 }205 //]206 await v.db.whenReady();207 });208 test("non simulated", async ()=>{209 //[210 await v.db.whenReady(); {211 v.foo = v.idb._dbs.foo;212 assert.same(v.foo._version, 2);213 after(v.TestModel.onChange(v.db.queueChange.bind(v.db)).stop);214 v.f1 = v.TestModel.create({_id: 'foo123', name: 'foo', age: 5, gender: 'm'});215 v.fIgnore = v.TestModel.createStopGap({216 _id: 'fooIgnore', name: 'foo ignore', age: 10, gender: 'f'});217 }218 await v.db.whenReady(); {219 refute(v.foo._store.TestModel.docs.fooIgnore);220 const iDoc = v.foo._store.TestModel.docs.foo123;221 assert.equals(iDoc, {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});222 v.f1.$update('age', 10);223 }224 await v.db.whenReady(); {225 const iDoc = v.foo._store.TestModel.docs.foo123;226 assert.equals(iDoc, {_id: 'foo123', name: 'foo', age: 10, gender: 'm'});227 v.f1.$remove();228 await v.db.whenReady();229 }230 await v.db.whenReady(); {231 const iDoc = v.foo._store.TestModel.docs.foo123;232 assert.equals(iDoc, undefined);233 }234 //]235 await v.db.whenReady();236 });237 });238 group("loadDoc", ()=>{239 /**240 * Insert a record into a model but ignore #queueChange for same record and do nothing if241 * record already in model unless model[stopGap$] symbol is true;242 *243 * If record is simulated make from change from client point-of-view else server POV.244 **/245 let called, onChange;246 before(()=>{247 api.protoMethod('loadDoc');248 onChange = ()=>{249 called = false;250 after(v.TestModel.onChange(dc => {251 v.db.queueChange(dc);252 called = true;253 }));254 };255 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {256 db.createObjectStore("TestModel");257 }});258 });259 beforeEach(()=>{260 called = false;261 v.simDocs = void 0;262 v.db.whenReady().then(()=>{263 v.simDocs = _=> Model._getProp(v.TestModel.dbId, 'TestModel', 'simDocs');264 session.state.incPending();265 after(_=> {session.state.decPending()});266 });267 TH.startTransaction();268 });269 afterEach(()=>{270 TH.rollbackTransaction();271 });272 test("simulated insert", async ()=>{273 const {db, TestModel} = v;274 const mockIndexedDB = v.idb;275 await v.db.whenReady();276 api.example(onChange);277 //[#278 const rec = {_id: 'foo123', name: 'foo', age: 5, gender: 'm', $sim: ['del', undefined]};279 db.loadDoc('TestModel', rec);280 await db.whenReady();281 const {foo} = mockIndexedDB._dbs;282 const {foo123} = TestModel.docs;283 assert.same(foo123.attributes, rec);284 assert.same(rec.$sim, undefined);285 assert(called);286 assert.equals(v.simDocs(), {foo123: ['del', undefined]});287 //]288 });289 test("non simulated insert", async ()=>{290 await v.db.whenReady();291 onChange();292 v.TestModel.onChange(v.oc = stub());293 assert.isTrue(util.isObjEmpty(v.simDocs()));294 v.db.loadDoc('TestModel', v.rec = {295 _id: 'foo123', name: 'foo', age: 5, gender: 'm'});296 await v.db.whenReady();297 v.foo = v.idb._dbs.foo;298 const {foo123} = v.TestModel.docs;299 assert.same(foo123.attributes, v.rec);300 assert(called);301 assert.isTrue(util.isObjEmpty(v.simDocs()));302 assert.calledWith(v.oc, DocChange.add(foo123, 'idbLoad'));303 });304 test("simulated update", async ()=>{305 await v.db.whenReady();306 v.db.loadDoc('TestModel', {307 _id: 'foo123', name: 'foo2', age: 5, gender: 'f', $sim: [{name: 'foo'}, undefined]});308 await v.db.whenReady();309 const {foo123} = v.TestModel.docs;310 assert.equals(foo123.name, 'foo2');311 assert.equals(v.simDocs(), {312 foo123: [{name: 'foo'}, undefined]});313 });314 test("simulated remove", async ()=>{315 await v.db.whenReady();316 v.db.loadDoc('TestModel', {_id: 'foo123', $sim: [{317 _id: 'foo123', name: 'foo2', age: 5, gender: 'f'}, undefined]});318 await v.db.whenReady();319 assert.same(v.TestModel.docs.foo123, undefined);320 assert.equals(v.simDocs(), {321 foo123: [{_id: 'foo123', name: 'foo2', age: 5, gender: 'f'}, undefined]});322 });323 group("with stopGap$", ()=>{324 beforeEach(()=>{325 v.db.whenReady().then(()=>{326 Query.insertFromServer(v.TestModel, {327 _id: 'foo123', name: 'stopGap', age: 5, gender: 'm'});328 v.foo123 = v.TestModel.docs.foo123;329 v.foo123[stopGap$] = true;330 });331 });332 test("simulated update", async ()=>{333 await v.db.whenReady();334 v.TestModel.onChange(v.oc = stub());335 v.db.loadDoc('TestModel', {336 _id: 'foo123', name: 'foo2', age: 5, gender: 'f', $sim: [{name: 'foo'}, undefined]});337 await v.db.whenReady();338 assert.equals(v.foo123.name, 'foo2');339 assert.equals(v.simDocs(), {340 foo123: [{name: 'foo'}, undefined]});341 assert.equals(v.foo123[stopGap$], undefined);342 assert.calledWith(v.oc, DocChange.change(343 m.is(v.foo123), {name: 'stopGap', gender: 'm'}, undefined));344 });345 test("non simulated update", async ()=>{346 await v.db.whenReady();347 v.TestModel.onChange(v.oc = stub());348 v.db.loadDoc('TestModel', {_id: 'foo123', name: 'foo2', age: 5, gender: 'f'});349 await v.db.whenReady();350 assert.equals(v.foo123.name, 'foo2');351 assert.isTrue(util.isObjEmpty(v.simDocs()));352 assert.calledWith(v.oc, DocChange.change(353 m.is(v.foo123), {name: 'stopGap', gender: 'm'}, 'idbLoad'));354 assert.equals(v.foo123[stopGap$], undefined);355 });356 test("simulated remove", async ()=>{357 await v.db.whenReady();358 v.TestModel.onChange(v.oc = stub());359 v.db.loadDoc('TestModel', {_id: 'foo123', $sim: [{360 _id: 'foo123', name: 'foo2', age: 5, gender: 'f'}, undefined]});361 await v.db.whenReady();362 assert.same(v.TestModel.docs.foo123, undefined);363 assert.equals(v.simDocs(), {364 foo123: [{_id: 'foo123', name: 'foo2', age: 5, gender: 'f'}, undefined]});365 assert.equals(v.foo123[stopGap$], undefined);366 assert.calledWith(v.oc, DocChange.delete(v.foo123, undefined));367 });368 });369 test("stopGap$", async ()=>{370 await v.db.whenReady();371 session.state.incPending();372 onChange();373 after(_=> {session.state.decPending()});374 v.db.loadDoc('TestModel', v.rec = {375 _id: 'foo123', name: 'foo', age: 5, gender: 'm'});376 await v.db.whenReady();377 v.foo = v.idb._dbs.foo;378 const {foo123} = v.TestModel.docs;379 assert.equals(v.foo._store.TestModel.docs, {});380 assert(called);381 called = false;382 v.db.loadDoc('TestModel', {_id: 'foo123', name: 'foo2', age: 5, gender: 'm'});383 await v.db.whenReady();384 assert.same(foo123.attributes, v.rec);385 assert.equals(foo123.name, 'foo');386 refute(called);387 v.TestModel.docs.foo123[stopGap$] = true;388 v.db.loadDoc('TestModel', {_id: 'foo123', name: 'foo2', age: 5, gender: 'm'});389 await v.db.whenReady();390 assert.equals(foo123.name, 'foo2');391 assert.same(v.TestModel.docs.foo123, foo123);392 assert.same(foo123.attributes, v.rec);393 assert.equals(foo123[stopGap$], undefined);394 assert(called);395 });396 });397 test("catchAll on open", ()=>{398 /**399 * Catch all errors from database actions400 **/401 const catchAll = stub();402 const open = spy(v.idb, 'open');403 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {404 db.createObjectStore("TestModel");405 }, catchAll});406 const req = open.firstCall.returnValue;407 req.onerror('my error');408 assert.calledWith(catchAll, 'my error');409 });410 test("catchAll on put", async ()=>{411 const catchAll = stub();412 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {413 db.createObjectStore("TestModel");414 }, catchAll});415 await v.db.whenReady();416 const transaction = spy(v.idb._dbs.foo, 'transaction');417 v.db.put('TestModel', v.rec = {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});418 assert.isFalse(v.db.isIdle);419 await v.db.whenReady();420 assert.calledOnceWith(transaction, ['TestModel'], 'readwrite');421 const t = transaction.firstCall.returnValue;422 t.oncomplete = null;423 const error = new Error('ev error');424 t.onerror(error);425 assert.isTrue(v.db.isReady);426 await v.db.whenReady();427 assert.calledWith(catchAll, error);428 });429 test("loadDocs", async ()=>{430 /**431 * Insert a list of records into a model. See {##loadDoc}432 **/433 const {TestModel} = v;434 const mockIndexeddb = v.idb;435 api.protoMethod('loadDocs');436 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {437 db.createObjectStore("TestModel");438 }});439 await db.whenReady();440 //[441 let called = false;442 TestModel.onChange(dc =>{db.queueChange(dc); called = true;});443 const recs = [444 {_id: 'foo123', name: 'foo', age: 5, gender: 'm'},445 {_id: 'foo456', name: 'bar', age: 10, gender: 'f'},446 ];447 db.loadDocs('TestModel', recs);448 await db.whenReady();449 const foo = v.idb._dbs.foo;450 assert.equals(TestModel.docs.foo123.attributes, recs[0]);451 assert.equals(TestModel.docs.foo456.attributes, recs[1]);452 assert.equals(foo._store.TestModel.docs, {});453 assert(called);454 //]455 });456 test("close", async ()=>{457 /**458 * Close a database. Once closed it may not be used anymore.459 **/460 api.protoMethod('close');461 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {462 db.createObjectStore("TestModel");463 }});464 v.db.close();465 v.db.put('TestModel', v.rec = {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});466 const ready = stub();467 try {468 await v.db.whenReady().then(ready);469 } catch(ex) {v.ex = ex;}470 v.foo = v.idb._dbs.foo;471 assert.equals(v.foo._store.TestModel.docs, {});472 refute.called(ready);473 assert.equals(v.ex.message, 'DB closed');474 });475 test("put", async ()=>{476 /**477 * Insert or update a record in indexedDB478 **/479 api.protoMethod();480 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {481 db.createObjectStore("TestModel");482 }});483 await v.db.whenReady();484 v.foo = v.idb._dbs.foo;485 TransQueue.transaction(() => {486 v.db.put('TestModel', v.rec = {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});487 assert.same(v.foo._store.TestModel.docs.foo123, undefined);488 });489 await v.db.whenReady();490 assert.equals(v.foo._store.TestModel.docs.foo123, v.rec);491 });492 test("delete", async ()=>{493 /**494 * Delete a record from indexedDB495 **/496 api.protoMethod();497 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {498 db.createObjectStore("TestModel");499 }});500 v.foo = v.idb._dbs.foo;501 await v.db.whenReady();502 v.foo._store.TestModel.docs = {503 foo123: {_id: 'foo123', name: 'foo', age: 5, gender: 'm'},504 foo456: {_id: 'foo456', name: 'foo 2', age: 10, gender: 'f'},505 };506 v.db.whenReady().then(() => {507 v.db.delete('TestModel', 'foo123');508 });509 await v.db.whenIdle();510 assert.equals(v.foo._store.TestModel.docs, {511 foo456: {_id: 'foo456', name: 'foo 2', age: 10, gender: 'f'}});512 });513 test("get", async ()=>{514 /**515 * Find a record in a {#koru/model/main} by its `_id`516 *517 **/518 api.protoMethod('get');519 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {520 db.createObjectStore("TestModel");521 }});522 await v.db.whenReady().then(() =>{523 after(v.TestModel.onChange(v.db.queueChange.bind(v.db)).stop);524 v.f1 = v.TestModel.create({_id: 'foo123', name: 'foo', age: 5, gender: 'm'});525 });526 const doc = await v.db.whenReady().then(()=> v.db.get("TestModel", "foo123"));527 assert.equals(doc, {_id: 'foo123', name: 'foo', age: 5, gender: 'm'});528 });529 test("getAll", async ()=>{530 /**531 * Find all records in a {#koru/model/main}532 *533 **/534 api.protoMethod('getAll');535 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {536 db.createObjectStore("TestModel");537 }});538 await v.db.whenReady();539 after(v.TestModel.onChange(v.db.queueChange.bind(v.db)).stop);540 TransQueue.transaction(() => {541 v.f1 = v.TestModel.create({_id: 'foo123', name: 'foo', age: 5, gender: 'm'});542 v.f2 = v.TestModel.create({_id: 'foo124', name: 'foo2', age: 10, gender: 'f'});543 });544 await v.db.whenReady();545 const docs = await v.db.getAll("TestModel");546 assert.equals(docs, [{547 _id: 'foo123', name: 'foo', age: 5, gender: 'm',548 }, {549 _id: 'foo124', name: 'foo2', age: 10, gender: 'f',550 }]);551 });552 group("with data", ()=>{553 beforeEach(()=>{554 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {555 db.createObjectStore("TestModel")556 .createIndex('name', 'name', {unique: false});557 }});558 v.db.whenReady().then(()=>{559 v.foo = v.idb._dbs.foo;560 v.t1 = v.foo._store.TestModel;561 v.t1.docs = {562 r2: v.r2 = {_id: 'r2', name: 'Ronald', age: 4},563 r1: v.r1 = {_id: 'r1', name: 'Ronald', age: 5},564 r3: v.r3 = {_id: 'r3', name: 'Allan', age: 3},565 r4: v.r4 = {_id: 'r4', name: 'Lucy', age: 7},566 };567 });568 });569 test("transaction", async ()=>{570 /**571 * Access to indexeddb transaction572 **/573 api.protoMethod('transaction');574 await v.db.whenReady();575 const t = v.db.transaction('TestModel', 'readwrite', v.opts = {576 oncomplete: stub(),577 onabort: stub(),578 });579 assert.same(t.oncomplete, v.opts.oncomplete);580 assert.same(t.onabort, v.opts.onabort);581 t.objectStore('TestModel').delete('r1');582 refute.called(v.opts.oncomplete);583 await v.db.whenReady();584 assert.called(v.opts.oncomplete);585 });586 test("count", async ()=>{587 /**588 * count records in a {#koru/model/main}589 *590 **/591 api.protoMethod('count');592 await v.db.whenReady();593 v.db.count('TestModel', IDBKeyRange.bound('r1', 'r4', false, true))594 .then(ans => v.ans = ans);595 await v.db.whenIdle();596 assert.same(v.ans, 3);597 });598 test("cursor", async ()=>{599 /**600 * Open cursor on an ObjectStore601 **/602 api.protoMethod('cursor');603 await v.db.whenReady();604 v.ans = [];605 v.db.cursor('TestModel', IDBKeyRange.bound('r1', 'r4', false, true), null, cursor => {606 if (cursor) {607 v.ans.push(cursor.value);608 cursor.continue();609 }610 });611 await v.db.whenReady();612 assert.equals(v.ans, [v.r1, v.r2, v.r3]);613 });614 test("Index", async ()=>{615 /**616 * Retreive a named index for an objectStore617 **/618 api.protoMethod('index');619 await v.db.whenReady();620 v.db.index("TestModel", "name")621 .getAll(IDBKeyRange.bound('Lucy', 'Ronald', false, true)).then(docs => v.ans = docs);622 v.db.index("TestModel", "name")623 .getAllKeys(IDBKeyRange.bound('Lucy', 'Ronald', false, true)).then(docs => v.ansKeys = docs);624 await v.db.whenIdle();625 assert.equals(v.ans, [v.r4]);626 assert.equals(v.ansKeys, ['r4']);627 v.db.index("TestModel", "name")628 .getAll().then(docs => v.ans = docs);629 v.db.index("TestModel", "name")630 .getAllKeys().then(docs => v.ansKeys = docs);631 await v.db.whenIdle();632 assert.equals(v.ans, [v.r3, v.r4, v.r1, v.r2]);633 assert.equals(v.ansKeys, ['r3', 'r4', 'r1', 'r2']);634 v.db.index("TestModel", "name")635 .count(IDBKeyRange.bound('Lucy', 'Ronald', false, false)).then(ans => v.ans = ans);636 await v.db.whenIdle();637 assert.equals(v.ans, 3);638 v.db.index("TestModel", "name")639 .get('Ronald').then(docs => v.ans = docs);640 await v.db.whenIdle();641 assert.equals(v.ans, v.r1);642 });643 test("index cursor", async ()=>{644 /**645 * Open a cursor on an index646 **/647 await v.db.whenReady();648 v.ans = [];649 v.db.index("TestModel", "name")650 .cursor(null, 'prev', cursor => {651 if (! cursor) return;652 v.ans.push(cursor.value);653 cursor.continue();654 });655 await v.db.whenReady();656 assert.equals(v.ans, [v.r2, v.r1, v.r4, v.r3]);657 });658 test("index keyCursor", async ()=>{659 /**660 * Open a keyCursor on an index661 **/662 await v.db.whenReady();663 v.ans = [];664 v.db.index("TestModel", "name")665 .keyCursor(null, 'prev', cursor => {666 if (! cursor) return;667 v.ans.push(cursor.primaryKey);668 cursor.continue();669 });670 await v.db.whenReady();671 assert.equals(v.ans, ['r2', 'r1', 'r4', 'r3']);672 });673 });674 test("deleteObjectStore", async ()=>{675 /**676 * Drop an objectStore and its indexes677 **/678 api.protoMethod('deleteObjectStore');679 v.db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {680 db.createObjectStore("TestModel")681 .createIndex('name', 'name', {unique: false});682 }});683 await v.db.whenReady();684 v.foo = v.idb._dbs.foo;685 v.db.deleteObjectStore('TestModel');686 refute(v.foo._store.TestModel);687 });688 test("deleteDatabase", async ()=>{689 /**690 * delete an entire database691 **/692 const mockIndexeddb = v.idb;693 api.method('deleteDatabase');694 const db = new QueryIDB({name: 'foo', version: 2, upgrade({db}) {695 db.createObjectStore("TestModel")696 .createIndex('name', 'name', {unique: false});697 }});698 await db.whenReady();699 //[700 let done = false;701 QueryIDB.deleteDatabase('foo').then(() => done = true);702 await db.whenIdle();703 assert(done);704 //]705 refute(mockIndexeddb._dbs.foo);706 });707 });...
apiSpec.js
Source:apiSpec.js
...34 }]));35 it("should prepare an event when functions are added", function() {36 $scope.$prepareForReady();37 expect($scope.$hasReadyEvents()).to.equal(false);38 $scope.$whenReady(39 function() { },40 function() { }41 );42 expect($scope.$hasReadyEvents()).to.equal(true);43 });44 it("should fire success when onReady", function(done) {45 $scope.$prepareForReady();46 $scope.$whenReady(done);47 $scope.$onReady();48 });49 it("should fire success when onReady and $q is custom", function(done) {50 $scope.$prepareForReady($q);51 $scope.$whenReady(done);52 $scope.$onReady();53 });54 it("should fire failure when onFailure", function(done) {55 $scope.$prepareForReady();56 $scope.$whenReady(function() {}, done);57 $scope.$onFailure();58 });59 it("should fire failure when onFailure and q is custom", function(done) {60 $scope.$prepareForReady($q);61 $scope.$whenReady(function() {}, done);62 $scope.$onFailure();63 });64 it("should have ready events when added", function() {65 $scope.$prepareForReady();66 $scope.$whenReady(function() {});67 expect($scope.$hasReadyEvents()).to.equal(true);68 });69 it("should not have ready events if nothing is provided", function() {70 expect($scope.$hasReadyEvents()).to.equal(false);71 $scope.$prepareForReady();72 expect($scope.$hasReadyEvents()).to.equal(false);73 $scope.$prepareForReady(null);74 expect($scope.$hasReadyEvents()).to.equal(false);75 $scope.$prepareForReady(null, null);76 expect($scope.$hasReadyEvents()).to.equal(false);77 });78 it("should not have ready events if only the failure callback is provided", function() {79 expect($scope.$hasReadyEvents()).to.equal(false);80 $scope.$prepareForReady(null, function() {});81 expect($scope.$hasReadyEvents()).to.equal(false);82 });83 it("should not set an event when nothing is provided", function() {84 $scope.$prepareForReady();85 expect($scope.$hasReadyEvents()).to.equal(false);86 $scope.$whenReady();87 expect($scope.$hasReadyEvents()).to.equal(false);88 });89 it("should not set an event when a non-function param is provided", function() {90 $scope.$prepareForReady();91 expect($scope.$hasReadyEvents()).to.equal(false);92 $scope.$whenReady('a');93 expect($scope.$hasReadyEvents()).to.equal(false);94 $scope.$whenReady(1);95 expect($scope.$hasReadyEvents()).to.equal(false);96 $scope.$whenReady([]);97 expect($scope.$hasReadyEvents()).to.equal(false);98 $scope.$whenReady(function() {}, 'a');99 expect($scope.$hasReadyEvents()).to.equal(false);100 $scope.$whenReady(function() {});101 expect($scope.$hasReadyEvents()).to.equal(true);102 });103 it("should not have ready events by default even if prepared", function() {104 $scope.$prepareForReady();105 expect($scope.$hasReadyEvents()).to.equal(false);106 });107 it("should be ready by default", function() {108 expect($scope.$isReady()).to.equal(true);109 });110 it("should not be ready after prepare", function() {111 $scope.$prepareForReady();112 expect($scope.$isReady()).to.equal(false);113 });114 it("should fire instantly when ready", function(done) {115 $scope.$prepareForReady();116 $scope.$onReady();117 $scope.$whenReady(done);118 });119 it("should fire instantly for success if not prepared", function(done) {120 $scope.$whenReady(done);121 });122 it("should not fire instantly for fail if not prepared", function() {123 var bool = false;124 $scope.$whenReady(null, function() {125 bool = true;126 });127 expect(bool).to.equal(false);128 });129 describe("Ordering", function() {130 var counter, inc, succ, response;131 beforeEach(function() {132 succ = function() {};133 response = '';134 counter = 0;135 inc = function() {136 counter++;137 };138 });139 it("should fire all the success events", function(done) {140 $scope.$prepareForReady();141 $scope.$whenReady(inc);142 $scope.$whenReady(inc);143 $scope.$whenReady(inc);144 $scope.$whenReady(function() {145 expect(counter).to.equal(3);146 done();147 });148 $scope.$onReady();149 });150 it("should fire the success events linearly when not prepared", function() {151 $scope.$whenReady(inc);152 expect(counter).to.equal(1);153 $scope.$whenReady(inc);154 expect(counter).to.equal(2);155 $scope.$whenReady(inc);156 expect(counter).to.equal(3);157 });158 it("should fire all the success events in order", function(done) {159 $scope.$prepareForReady();160 $scope.$whenReady(function() {161 response += 'a'162 });163 $scope.$whenReady(function() {164 response += 'b'165 });166 $scope.$whenReady(function() {167 response += 'c'168 });169 $scope.$whenReady(function() {170 expect(response).to.equal('abc');171 done();172 });173 $scope.$onReady();174 });175 it("should fire all the fail events", function(done) {176 $scope.$prepareForReady();177 $scope.$whenReady(succ, inc);178 $scope.$whenReady(succ, inc);179 $scope.$whenReady(succ, inc);180 $scope.$whenReady(succ, function() {181 expect(counter).to.equal(3);182 done();183 });184 $scope.$onFailure();185 });186 it("should fire success for all the fail events linearly when not prepared", function() {187 $scope.$whenReady(succ, inc);188 expect(counter).to.equal(0);189 $scope.$whenReady(succ, inc);190 expect(counter).to.equal(0);191 $scope.$whenReady(succ, inc);192 expect(counter).to.equal(0);193 });194 it("should fire all the fail events in order", function(done) {195 $scope.$prepareForReady();196 $scope.$whenReady(succ, function() {197 response += 'a'198 });199 $scope.$whenReady(succ, function() {200 response += 'b'201 });202 $scope.$whenReady(succ, function() {203 response += 'c'204 });205 $scope.$whenReady(succ, function() {206 expect(response).to.equal('abc');207 done();208 });209 $scope.$onFailure();210 });211 });212 });...
whenReady.spec.js
Source:whenReady.spec.js
1const {WhenReady} = require('./whenReady');2const {assert} = require('chai');3describe('WhenReady Tests', () => {4 it('should call a Function when something is ready', (done) => {5 let start = false;6 let calls = 0;7 WhenReady({8 timeout: 10,9 maxCalls: 50,10 },11 (a, b) => {12 assert.equal(a, 1);13 assert.equal(b, 1);14 return start;15 },16 (a, b) => {17 calls++;18 assert.isTrue(start);19 return a + b;20 }, 1, 121 ).then(res => {22 assert.equal(calls, 1);23 assert.equal(res, 2);24 done();25 });26 setTimeout(() => {27 start = true;28 }, 100);29 });30 it('exit on max calls', (done) => {31 let start = false;32 let guardCalls = 0;33 let calls = 0;34 WhenReady({35 timeout: 10,36 maxCalls: 5,37 }, () => {38 guardCalls++;39 return false;40 }, (a, b) => {41 calls++;42 return a+b;43 }, 1, 1).then(res => {44 assert.isNull(res);45 assert.equal(guardCalls, 5);46 assert.equal(calls, 0);47 done();48 });49 });50 it('without guard call function immediately', (done) => {51 let start = false;52 let calls = 0;53 WhenReady({54 timeout: 10,55 maxCalls: 5,56 }, null, (a, b) => {57 calls++;58 return a+b;59 }, 1, 1).then(res => {60 assert.equal(res, 2);61 assert.equal(calls, 1);62 done();63 });64 });65 it('default options', (done) => {66 let start = false;67 let calls = 0;68 WhenReady(null, () => start, (a, b) => {69 calls++;70 return a+b;71 }, 1, 1).then(res => {72 assert.equal(res, 2);73 assert.equal(calls, 1);74 done();75 });76 setTimeout(() => start = true, 40);77 });78 it('no negative timeout and maxCalls', (done) => {79 let start = false;80 let calls = 0;81 WhenReady({82 timeout: -1,83 maxCalls: -1,84 }, () => start, (a, b) => {85 calls++;86 return a+b;87 }, 1, 1).then(res => {88 assert.equal(res, 2);89 assert.equal(calls, 1);90 done();91 });92 setTimeout(() => start = true, 40);93 });94 it('accept async functions', (done) => {95 let start = false;96 let calls = 0;97 WhenReady({98 timeout: -1,99 maxCalls: -1,100 }, async () => {101 return await new Promise((resolve) => resolve(start));102 }, async (a, b) => {103 calls++;104 return await new Promise((resolve) => resolve(a+b));105 }, 1, 1).then(res => {106 assert.equal(res, 2);107 assert.equal(calls, 1);108 done();109 });110 setTimeout(() => start = true, 40);111 });112 it('can fire multiple times', (done) => {113 let start = false;114 let calls = 0;115 const todo = async () => {116 return await WhenReady({117 timeout: -1,118 maxCalls: -1,119 }, () => {120 return start;121 }, async (a, b) => {122 calls++;123 return await new Promise((resolve) => resolve(a+b));124 }, 1, 1);125 };126 todo().then(res => {127 assert.equal(res, 2);128 assert.equal(calls, 2);129 });130 setTimeout(() => {131 start = true;132 todo().then(res => {133 assert.equal(res, 2);134 assert.equal(calls, 1);135 });136 setTimeout(() => {137 todo().then(res => {138 assert.equal(res, 2);139 assert.equal(calls, 3);140 done();141 });142 }, 50);143 }, 50);144 });...
API.js
Source:API.js
1/*function APIAction(url, func, whenReady){2 var f;3 if (whenReady === undefined){4 f = function(){}5 }else{6 f = whenReady;7 }8 var xmlhttp = new XMLHttpRequest();9 xmlhttp.onreadystatechange = function() {10 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {11 var myArr = JSON.parse(xmlhttp.responseText);12 func(myArr);13 f();14 }15 }16 xmlhttp.open("GET", url, true);17 xmlhttp.timeout = 30000; //miliseconds18 xmlhttp.ontimeout = function () {19 $('#noconn').remove();20 $('noscript').after(21 '<div id="noconn" class="alert alert-danger" role="alert">' +22 '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>' +23 '<span class="sr-only">Error:</span>' + 24 'No es posible establecer una conexión con el servidor. Por favor, inténtelo más tarde.' +25 '</div>'26 );27 KillLoader();28 }29 xmlhttp.send();30 return xmlhttp;31}*/32/*function APIAction(url_g, func, whenReady){33 var f;34 if (whenReady === undefined){35 f = function(){}36 }else{37 f = whenReady;38 }39 $.ajax({40 url: url_g,41 dataType: "jsonp",42 timeout: 30000,43 global: true44 }).done(function (data) {45 func(data);46 f();47 //if (!callbacks) {48 // callbacks = {};49 //}50 //if (data.error && callbacks.hasOwnProperty('error')) {51 // callbacks.error(data);52 // return;53 //}54 //if (callbacks.hasOwnProperty('success')) {55 // callbacks.success(data);56 //}57 }).fail(function () {58 $('#noconn').remove();59 $('noscript').after(60 '<div id="noconn" class="alert alert-danger" role="alert">' +61 '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>' +62 '<span class="sr-only">Error:</span>' + 63 'No es posible establecer una conexión con el servidor. Por favor, inténtelo más tarde.' +64 '</div>'65 );66 KillLoader();67 })68}*/69/* WORKS TOO!70function APIAction(url, func, whenReady){71 var f;72 if (whenReady === undefined){73 f = function(){}74 }else{75 f = whenReady;76 }77 $.getJSON(url, function(data){78 func(data);79 f();80 });81}*/82function APIAction(url, func, whenReady){83 var f;84 if (whenReady === undefined){85 f = function(){}86 }else{87 f = whenReady;88 }89 $.ajax({90 dataType: "json",91 url: url,92 timeout: 30000,93 success: function(data){94 if (data.hasOwnProperty('error')){95 Error('Ha ocurrido un error procesando la solicitud. Por favor, inténtelo más tarde.');96 } else { 97 func(data);98 f();99 }100 }101 }).fail(function () {102 $('#noconn').remove();103 $('noscript').after(104 '<div id="noconn" class="alert alert-danger" role="alert">' +105 '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>' +106 '<span class="sr-only">Error:</span>' + 107 'No es posible establecer una conexión con el servidor. Por favor, inténtelo más tarde.' +108 '</div>'109 );110 KillLoader();111 });...
server_spec.js
Source:server_spec.js
1import {Deferred, withUnhandledRejection} from '../spec_helper';2import request from 'supertest';3import {createServer} from '../../dist/lib/server';4describe('Server', function() {5 let app, files;6 beforeEach(function() {7 files = {8 'specRunner.html': 'The Spec Runner'9 };10 });11 describe('when the server is not passed options', function() {12 beforeEach(function() {13 app = createServer(files);14 });15 describe('GET /', function() {16 it.async('renders the spec runner', async function() {17 const res = await request(app).get('/').expect(200);18 expect(res.text).toContain('The Spec Runner');19 });20 });21 describe('GET *', function() {22 describe('with a file that exists', function() {23 beforeEach(function() {24 files['foo.js'] = 'Foo Content';25 });26 it.async('renders the file', async function() {27 const res = await request(app).get('/foo.js').expect(200);28 expect(res.text).toContain('Foo Content');29 });30 });31 describe('with a file that does not exist', function() {32 it.async('returns 404', async function() {33 const res = await request(app).get('/bar.js');34 expect(res.statusCode).toBe(404);35 });36 });37 });38 });39 describe('when the server is passed whenReady', function() {40 let whenReady;41 beforeEach(function() {42 whenReady = new Deferred();43 app = createServer(files, {whenReady: () => whenReady});44 });45 describe('GET /', function() {46 describe('whenReady is resolved', function() {47 it.async('renders the valid version of spec runner', async function() {48 setTimeout(function() {49 files['specRunner.html'] = 'The New Version';50 whenReady.resolve();51 }, 100);52 const res = await request(app).get('/').expect(200);53 expect(res.text).toContain('The New Version');54 });55 describe('when there is an error', () => {56 withUnhandledRejection();57 it.async('does not render intermediate invalid states', async function() {58 setTimeout(function() {59 files['specRunner.html'] = 'The Bad Version';60 whenReady.reject(new Error('some error'));61 whenReady = new Deferred();62 }, 100);63 setTimeout(function() {64 files['specRunner.html'] = 'The Good Version';65 whenReady.resolve();66 }, 200);67 const res = await request(app).get('/').expect(200);68 expect(res.text).toContain('The Good Version');69 });70 });71 });72 });73 });...
jasmine-plugin_spec.js
Source:jasmine-plugin_spec.js
...15 doneSpy = jasmine.createSpy('done');16 failSpy = jasmine.createSpy('fail');17 });18 it('does not resolve or reject the promise', function(done) {19 subject.whenReady().then(doneSpy, failSpy);20 expect(doneSpy).not.toHaveBeenCalled();21 expect(failSpy).not.toHaveBeenCalled();22 done();23 });24 describe('when the done event is emitted', function() {25 beforeEach(function() {26 compiler.emit('done');27 });28 it.async('resolves the promise', async function() {29 await subject.whenReady().then(doneSpy, failSpy);30 expect(doneSpy).toHaveBeenCalled();31 });32 describe('and then the invalid event is emitted', function() {33 it('resets the promise', function(done) {34 compiler.emit('invalid');35 subject.whenReady().then(doneSpy, failSpy);36 setTimeout(function() {37 expect(doneSpy).not.toHaveBeenCalled();38 expect(failSpy).not.toHaveBeenCalled();39 done();40 }, 1);41 });42 });43 });44 describe('when the invalid event is emitted', function() {45 it('rejects the promise', async function(done) {46 try {47 const whenReady = subject.whenReady();48 whenReady.then(doneSpy, failSpy);49 compiler.emit('invalid');50 await whenReady;51 } finally {52 expect(failSpy).toHaveBeenCalled();53 done();54 }55 });56 });57 });...
server.js
Source:server.js
...11 console.log(message);12 }13}14function renderFile(res, files, pathname, whenReady) {15 whenReady()16 .then(function() {17 pathname = decodeURIComponent(pathname);18 if (pathname && files[pathname]) {19 res.status(200).type(mime.lookup(pathname));20 const stream = new PassThrough();21 stream.end(files[pathname]);22 stream.pipe(res);23 return;24 }25 res.status(404).send('File not Found');26 }, function() {27 renderFile(res, files, pathname, whenReady);28 });29}...
acute.whenReady.spec.js
Source:acute.whenReady.spec.js
...3 beforeEach(module('acute.whenReady'));4 describe('whenReady', function () {5 it('should not call callback when values are undefined', inject(function (whenReady) {6 var readyFunc, callback = sinon.stub();7 readyFunc = whenReady(callback);8 readyFunc(undefined, undefined);9 expect(callback).not.toHaveBeenCalled();10 }));11 it('should call callback when current value is defined', inject(function (whenReady) {12 var readyFunc, callback = sinon.stub();13 readyFunc = whenReady(callback);14 readyFunc('curr', undefined);15 expect(callback).toHaveBeenCalledWithExactly('curr', undefined);16 }));17 it('should call callback when values are defined', inject(function (whenReady) {18 var readyFunc, callback = sinon.stub();19 readyFunc = whenReady(callback);20 readyFunc('curr', 'prev');21 expect(callback).toHaveBeenCalledWithExactly('curr', 'prev');22 }));23 });...
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('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('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', function () {2 it('test', function () {3 cy.get('input[name="q"]').type('Cypress')4 cy.get('input[value="Google Search"]').click()5 cy.wait(5000)6 cy.get('h3 > a').should('have.text', 'Cypress').click()7 cy.wait(5000)8 cy.get('h1').should('have.text', 'Cypress')9 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()10 cy.wait(5000)11 cy.get('h1').should('have.text', 'JavaScript End to End Testing')12 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()13 cy.wait(5000)14 cy.get('h1').should('have.text', 'JavaScript End to End Testing')15 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()16 cy.wait(5000)17 cy.get('h1').should('have.text', 'JavaScript End to End Testing')18 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()19 cy.wait(5000)20 cy.get('h1').should('have.text', 'JavaScript End to End Testing')21 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()22 cy.wait(5000)23 cy.get('h1').should('have.text', 'JavaScript End to End Testing')24 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()25 cy.wait(5000)26 cy.get('h1').should('have.text', 'JavaScript End to End Testing')27 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()28 cy.wait(5000)29 cy.get('h1').should('have.text', 'JavaScript End to End Testing')30 cy.get('a[title="Cypress.io"]').should('have.text', 'Cypress.io').click()31 cy.wait(5000)32 cy.get('h1').should('have.text', 'JavaScript End to End
Using AI Code Generation
1describe('When ready', () => {2 it('Should wait for the page to load', () => {3 cy.get('#query-btn').click()4 cy.get('.network-put-comment').should('contain', 'Button')5 })6})7describe('When ready', () => {8 it('Should wait for the page to load', () => {9 cy.get('#query-btn').click()10 cy.get('.network-put-comment').should('contain', 'Button')11 })12})13describe('When ready', () => {14 it('Should wait for the page to load', () => {15 cy.get('#query-btn').click()16 cy.get('.network-put-comment').should('contain', 'Button')17 })18})19describe('When ready', () => {20 it('Should wait for the page to load', () => {21 cy.get('#query-btn').click()22 cy.get('.network-put-comment').should('contain', 'Button')23 })24})25describe('When ready', () => {26 it('Should wait for the page to load', () => {27 cy.get('#query-btn').click()28 cy.get('.network-put-comment').should('contain', 'Button')29 })30})31describe('When ready', () => {32 it('Should wait for the page to load', () => {33 cy.get('#query-btn').click()34 cy.get('.network-put-comment').should('contain', 'Button')35 })36})37describe('When ready', () => {38 it('Should wait for the page to load', () => {39 cy.get('#query-btn').click()
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!!