forked from meganz/Dexie.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests-exception-handling.js
535 lines (489 loc) · 22.3 KB
/
tests-exception-handling.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import Dexie from 'dexie';
import {module, stop, start, asyncTest, equal, ok} from 'QUnit';
import {resetDatabase, spawnedTest} from './dexie-unittest-utils';
var db = new Dexie("TestDBException");
db.version(1).stores({ users: "id,first,last,&username,&*email,*pets" });
db.on("populate", function (trans) {
var users = trans.table("users");
users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["[email protected]", "[email protected]"], pets: ["dog"] });
users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["[email protected]"], pets: [] });
});
db.on("error", function (e) {
ok(false, "An error bubbled out to the db.on('error'). Should not happen because all tests should catch their errors themselves. " + e);
});
module("exception-handling", {
setup: function () {
stop();
resetDatabase(db).catch(function (e) {
ok(false, "Error resetting database: " + e);
}).finally(start);
},
teardown: function () {
}
});
spawnedTest("transaction should abort on collection error", function*(){
yield db.transaction("rw", db.users, function*() {
let id = yield db.users.add({id: 3, first: "Foo", last: "Bar", username: "foobar"});
equal (id, 3);
yield db.users.where('id').equals(null).toArray();
ok(false, "Should not come here");
}).catch(e => {
ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e);
});
equal (yield db.users.where('first').equals("Foo").count(), 0, "Should not have succeeded to add when transaction was aborted");
yield db.transaction("rw", db.users, function() {
db.users.add({id: 3, first: "Foo", last: "Bar", username: "foobar"});
db.users.where('id').equals(null).toArray(res=> {
ok(false, "Not possible to query null");
});
}).then(()=>{
ok(false, "Transaction shouldnt commit");
}).catch(e => {
ok(true, "Got error because WhereClause.equals(null) should throw TypeError");
});
equal (yield db.users.where('first').equals("Foo").count(), 0, "Should not have succeeded to add when transaction was aborted");
});
asyncTest("eventError-transaction-catch", function () {
db.transaction("rw", db.users, function () {
db.users.add({ id: 100, username: "dfahlander" }).then(function () {
ok(false, "Should not be able to add two users with same username");
});
}).then(function () {
ok(false, "Transaction should not complete since an error should have occurred");
}).catch(function (e) {
ok(true, "Got transaction error: " + e);
}).finally(start);
});
asyncTest("eventError-request-catch", function () {
db.transaction("rw", db.users, function () {
db.users.add({ id: 100, username: "dfahlander" }).then(function () {
ok(false, "Should not be able to add two users with same username");
}).catch(function (e) {
ok(true, "Got request error: " + e);
});
db.users.add({ id: 101, first: "Trazan", last: "Apansson", username: "tapan", email: ["[email protected]"], pets: ["monkey"] }).then(function (id) {
ok(id > 2, "Could continue transaction and add Trazan since last error event was catched");
});
}).then(function () {
ok(true, "Transaction should complete since the only error that occurred was catched");
}).catch(function (e) {
ok(false, "Should not get transaction error since we have catched the error. Got Transaction error: " + e);
}).finally(start);
});
asyncTest("exceptionThrown-transaction-catch", function () {
db.transaction("r", db.users, function () {
throw new SyntaxError("Why not throw an exception for a change?");
}).then(function () {
ok(false, "Transaction should not complete since an error should have occurred");
}).catch(TypeError, function (e) {
ok(false, "Should not happen. The thrown error was not a TypeError");
}).catch(SyntaxError, function (e) {
ok(true, "Transaction got SyntaxError: " + e);
}).catch(function (e) {
ok(false, "Should not come here! The error should already have been catched above()");
}).finally(start);
});
asyncTest("exceptionThrown-request-catch", function () {
db.transaction("r", db.users, function () {
db.users.where("username").equals("apa").toArray(function () {
db.users.where("username").equals("kceder").toArray().then(function () {
return "a";
}).then(function () {
NonExistingSymbol.EnotherIdioticError = "Why not make an exception for a change?";
});
});
}).then(function () {
ok(false, "Transaction should not complete since an error should have occurred");
}).catch(function (e) {
ok(true, "Transaction got error: " + e);
}).finally(start);
});
asyncTest("exceptionThrown-iteration-should-abort-when-using-hook", function () {
db.users.hook('deleting', function () {
// Testing with
})
db.transaction('rw', db.users, function () {
function deleteKarls() {
db.users.toCollection().modify(function (user) {
delete this.value;
throw "Throwing something";
});
}
db.users.delete(1);
deleteKarls();
}).then(function () {
ok(false, "Transaction should not complete!");
}).catch(function (err) {
ok(true, "Transaction aborted");
}).finally(start);
});
asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () {
db.users.hook('deleting', function () {
// Testing with
})
db.transaction('rw', db.users, function () {
function deleteKarls() {
db.users.toCollection().modify(function (user) {
delete this.value;
throw "Throwing something";
}).catch(function (err) {
// Catching error should prevent transaction from aborting.
});
}
db.users.delete(1);
deleteKarls();
}).then(function () {
ok(true, "Transaction completed");
}).catch(function (err) {
ok(false, "Transaction should not abort!");
}).finally(start);
});
/*asyncTest("promise-test", function () {
var p = new Dexie.Promise(function (resolve, reject) {
setTimeout(function () {
reject("apa error");
}, 0);
});
p.catch(function (err) {
return Dexie.Promise.reject(err);
});
p.then(function(){}).catch(function (err) {
return Dexie.Promise.reject(err);
});
p.onuncatched = function () {
debugger;
}
p.finally(start);
});*/
asyncTest("exception in upgrader", function () {
// Create a database:
var db = new Dexie("TestUpgrader");
db.version(1).stores({ cars: "++id,name,brand" });
db.open().then(function(){
// Once it opens, close it and create an upgraded version that will fail to upgrade.
db.close();
db = new Dexie("TestUpgrader");
db.version(1).stores({ cars: "++id,name,brand" });
db.version(2).upgrade(function (trans) { trans.cars.add({ name: "My car", brand: "Pegeut" }); });
db.version(3).upgrade(function (trans) {
throw new Error("Oops. Failing in upgrade function");
});
return db.open();
}).catch(function (err) {
// Got error
ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err);
// Create 3rd instance of db that will only read from the existing DB.
// What we want to check here is that the DB is there but is still
// only on version 1.
db = new Dexie("TestUpgrader");
return db.open();
}).then(function (){
equal(db.verno, 1, "Database is still on version 1 since it failed to upgrade to version 2.");
}).finally(function () {
db.delete().then(start);
});
});
asyncTest("exception in on('populate')", function () {
// Create a database:
var db = new Dexie("TestUpgrader");
db.version(1).stores({ cars: "++id,name,brand" });
db.on('populate', function () {
throw new Error("Oops. Failing in upgrade function");
});
db.open().catch(function (err) {
// Got error
ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err);
// Create 3rd instance of db that will only read from the existing DB.
// What we want to check here is that the DB is there but is still
// only on version 1.
db = new Dexie("TestUpgrader");
return db.open();
}).then(function () {
ok(false, "The database should not have been created");
}).catch(function (err) {
ok(err.toString().indexOf("doesnt exist") != -1, "The database doesnt exist");
}).finally(function () {
db.delete().then(start);
});
});
asyncTest("catch-all with db.on('error')", 3, function () {
if (typeof idbModules !== 'undefined' && Dexie.dependencies.indexedDB === idbModules.shimIndexedDB) {
// Using indexedDBShim.
ok(false, "This test would hang with IndexedDBShim as of 2015-05-07");
start();
return;
}
var ourDB = new Dexie("TestDB2");
ourDB.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" });
ourDB.on("populate", function () {
ourDB.users.add({ first: "Daniel", last: "Fahlenius", username: "dfahlenius", email: ["[email protected]", "[email protected]"], pets: ["dog"] });
ourDB.users.add({ first: "Carl", last: "Cedersköld", username: "cceder", email: ["[email protected]"], pets: [] });
});
var errorCount = 0;
ourDB.on("error", function (e) {
ok(errorCount < 3, "Uncatched error successfully bubbled to ourDB.on('error'): " + e);
if (++errorCount == 3) {
Dexie.Promise.on('error').unsubscribe(swallowPromiseOnError);
ourDB.delete().then(start);
}
});
function swallowPromiseOnError(e){
}
Dexie.Promise.on('error', swallowPromiseOnError); // Just to get rid of default error logs for not catching.
ourDB.open();
ourDB.transaction("rw", ourDB.users, function () {
ourDB.users.add({ username: "dfahlenius" }).then(function () {
ok(false, "Should not be able to add two users with same username");
});
}).then(function () {
ok(false, "Transaction should not complete since errors wasnt catched");
});
ourDB.transaction("rw", ourDB.users, function () {
ourDB.users.add({ username: "dfahlenius" }).then(function () {
ok(false, "Should not be able to add two users with same username");
});
}).then(function () {
ok(false, "Transaction should not complete since errors wasnt catched");
});
ourDB.transaction("rw", ourDB.users, function () {
ourDB.users.add({ username: "dfahlenius" }).then(function () {
ok(false, "Should not be able to add two users with same username");
});
}).then(function () {
ok(false, "Transaction should not complete since errors wasnt catched");
});
});
asyncTest("Issue #32: db.on('error') doesnt catch 'not found index' DOMExceptions", function () {
var ourDB = new Dexie("TestDB2");
new Dexie.Promise(function (finalResolve) {
ourDB.version(1).stores({ users: "++id" });
ourDB.on("populate", function() {
db.users.add({ id: 100, first: "David", last: "Fahlander" });
});
var errorHasBubbled = false;
ourDB.on("error", function(e) {
errorHasBubbled = true;
ok(true, "Uncatched error successfully bubbled to db.on('error'): " + e);
finalResolve();
});
ourDB.open().then(function () {
// Make the db fail by not finding a correct index:
ourDB.users.where("I am a little frog!").equals(18).toArray();
setTimeout(function() {
if (!errorHasBubbled) {
ok(false, "Timeout! Error never bubbled to db.on('error')");
}
finalResolve();
}, 300);
});
}).then(function() {
ourDB.delete().then(start);
});
});
asyncTest("Error in on('populate') should abort database creation", function () {
var popufail = new Dexie("PopufailDB");
popufail.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" });
popufail.on('populate', function () {
popufail.users.add({ first: NaN, last: undefined, username: function () { } }).catch(function (e) {
ok(true, "Got error when catching add() operation: " + e);
return Dexie.Promise.reject(e);
});
});
popufail.open().catch(function (err) {
ok(true, "Got error (as expected):" + err);
});
popufail.users.count(function (count) {
ok(false, "Could query database even though an error happened in the populate event!");
}).catch(function (err) {
ok(true, "Got error when trying to query: " + err);
}).finally(function () {
popufail.delete();
start();
});
});
asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(A)", function () {
function CustomError() { }
var wasCatched = false;
new Dexie.Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error("apa"));
}, 0);
}).then(function () {
ok(false, "Should not come here");
}).catch(CustomError, function (e) {
ok(false, "Should not come here");
}).catch(function (e) {
wasCatched = true;
}).finally(function () {
ok(wasCatched, "The error was catched in the generic catcher");
start();
});
});
asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(B)", function () {
function CustomError() { }
var wasCatched = false;
Dexie.Promise.resolve(null).then(function () {
throw new Error("apa");
}).then(function () {
ok(false, "Should not come here");
}).catch(CustomError, function (e) {
ok(false, "Should not come here");
}).catch(function (e) {
wasCatched = true;
}).finally(function () {
ok(wasCatched, "The error was catched in the generic catcher");
start();
});
});
asyncTest("Issue #67 - Exception can be thrown in WhereClause methods", function() {
try {
Dexie.Promise.all([
// WhereClause.equals()
db.users.where('first').equals(false) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.equals() returned as a failed Promise and not an exception.");
}),
// WhereClause.above()
db.users.where('first').above(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.above() returned as a failed Promise and not an exception.");
}),
// WhereClause.aboveOrEqual()
db.users.where('first').aboveOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.aboveOrEqual() returned as a failed Promise and not an exception.");
}),
// WhereClause.below()
db.users.where('first').below(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.below() returned as a failed Promise and not an exception.");
}),
// WhereClause.belowOrEqual()
db.users.where('first').belowOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.belowOrEqual() returned as a failed Promise and not an exception.");
}),
// WhereClause.anyOf()
db.users.where('first').anyOf([undefined, null, false]) // Using a non-valid key (undefined, false) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.anyOf() returned as a failed Promise and not an exception.");
}),
// WhereClause.between()
db.users.where('first').between(false, true) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.between() returned as a failed Promise and not an exception.");
}),
// WhereClause.equalsIgnoreCase()
db.users.where('first').equalsIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.equalsIgnoreCase() returned as a failed Promise and not an exception.");
}),
// WhereClause.startsWith()
db.users.where('first').startsWith(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.startsWith() returned as a failed Promise and not an exception.");
}),
// WhereClause.startsWithIgnoreCase()
db.users.where('first').startsWithIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
.toArray()
.catch(function(err) {
ok(true, "Invalid key passed to WhereClause.startsWithIgnoreCase() returned as a failed Promise and not an exception.");
})
]).catch(function() {
ok(false, "No promise should finally reject because we catch them all explicitely.")
}).finally(start);
} catch (ex) {
ok(false, "Error was not encapsulated as a Promise failure: " + (ex.stack || ex));
start();
}
});
asyncTest("Issue #67 - Regression test - Transaction still fails if error in key", function () {
db.transaction('rw', db.users, function () {
db.users.where('first').above("").delete().then(function (num) {
ok(true, num + " users deleted");
db.users.where('first').above(undefined).delete();
});
}).then(function() {
ok(false, "Transaction should not commit when we an unhandled error has happened");
}).catch(function(err) {
ok(true, "Good, transaction failed as expected");
}).finally(start);
});
asyncTest("Issue #69 Global exception handler for promises", function () {
var errorList = [];
function globalRejectionHandler(e) {
console.log("Got error: " + e);
if (errorList.indexOf(e) === -1) // Current implementation: accept multiple redundant triggers
errorList.push(e);
}
Dexie.Promise.on("error", globalRejectionHandler);
// The most simple case: Any Promise reject that is not catched should
// be handled by the global error listener.
new Dexie.Promise(function(resolve, reject) {
reject("first error (by reject)");
});
// Also if the rejection was caused by a throw...
new Dexie.Promise(function() {
throw "second error (throw)";
});
// But when catched it should not trigger the global event:
new Dexie.Promise(function(resolve, reject) {
reject("third error (catched)");
}).catch(function(e) {
ok(true, "Catched error explicitely: " + e);
});
// If catching an explicit error type that was not thrown, it should be triggered
new Dexie.Promise(function(resolve, reject) {
reject("Simple error 1");
}).catch(TypeError, function(e) {
ok(false, "Error should not have been TypeError");
});// Real error slip away... should be handled by global handler
new Dexie.Promise(function(resolve, reject) {
reject(new TypeError("Type Error 1"));
}).catch(TypeError, function(e) {
ok(true, "Catched the TypeError");
// Now we have handled it. Not bubble to global handler!
});
// With finally, it should yet trigger the global event:
new Dexie.Promise(function(resolve, reject) {
reject("forth error (uncatched but with finally)");
}).finally(function() {
// From issue #43:
// Prepare by cleaning up any unfinished previous run:
Dexie.delete("testdb").then(function() {
// Now just do some Dexie stuff...
var db = new Dexie("testdb");
db.version(1).stores({ table1: "id" });
db.on('error', function(err) {
// Global 'db' error handler (will never be called 'cause the error is not in a transaction)
console.log("db.on.error: " + err);
errorList.push("Got db.on.error: " + err);
});
db.open().then(function() {
console.log("before");
throw "FOO"; // Here a generic error is thrown (not a DB error)
console.log("after");
});
db.delete().finally(function() {
equal(errorList.length, 5, "THere should be 4 global errors triggered");
equal(errorList[0], "first error (by reject)", "first error (by reject)");
equal(errorList[1], "second error (throw)", "second error (throw)");
equal(errorList[2], "Simple error 1", "Simple error 1");
equal(errorList[3], "forth error (uncatched but with finally)", "forth error (uncatched but with finally)");
equal(errorList[4], "FOO", "FOO");
// cleanup:
Dexie.Promise.on("error").unsubscribe(globalRejectionHandler);
start();
});
});
});
});