forked from indexeddbshim/IndexedDBShim
/
test-utils.js
354 lines (325 loc) · 13.2 KB
/
test-utils.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
/* eslint-env mocha */
/* globals env */
/* eslint-disable no-var */
(function () {
'use strict';
var databaseNamePrefix = 'indexeddbshim_test_database_';
var databaseSuffix = ''; // '.sqlite' now added automatically by default
var dbNameCounter = 0;
var util;
/**
* This function runs before every test.
*/
beforeEach(function () {
// Track the current test
util.currentTest = this.currentTest;
// A list of databases created during this test
util.currentTest.databases = [];
// Increase the slowness threshold
util.currentTest.slow(300);
});
/**
* This function runs after every test
*/
afterEach(function (done) {
// Delete all databases that were created during this test
util.asyncForEach(util.currentTest.databases, done, function (dbName) {
return env.indexedDB.deleteDatabase(dbName);
});
});
util = window.util = {
sampleData: {
/**
* A custom class, used to test the IndexedDB structured cloning algorithm
*/
Person: Person,
/**
* A very long string :)
*/
veryLongString: new Array(1001).join('1234567890') // 10,000 characters
},
/**
* Skips the given test if the given condition is true.
* @param {boolean} condition
* @param {string} title
* @param {function} test
*/
skipIf (condition, title, test) {
if (condition) {
it.skip(title, test);
} else {
it(title, test);
}
},
/**
* Creates a test database with one or more pre-defined schema items.
*
* @param {...string} schema One or more pre-defined schema items. (see {@link createSchemaItem})
* @param {function} done `function(err, db)`
*/
createDatabase (schema, done) {
schema = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
done = arguments[arguments.length - 1];
util.generateDatabaseName(function (err, dbName) {
// Open the database
var open = env.indexedDB.open(dbName, 1);
open.onerror = open.onblocked = function (event) {
var err;
try {
err = event.target.error;
console.error(err.message);
} finally {
done(err || 'Unknown Error');
}
};
// Add the specified schema items
open.onupgradeneeded = function () {
open.transaction.onerror = open.onerror;
schema.forEach(function (schemaItem) {
createSchemaItem(open.transaction, schemaItem);
});
};
// Done!
open.onsuccess = function () {
done(err, open.result);
};
});
},
/**
* Returns all data in the given object store or index.
*
* @param {IDBObjectStore|IDBIndex} store The object store or index
* @param {function} done `function(err, data)`
*/
getAll (store, done) {
util.query(store, done);
},
/**
* Queries data in the given object store or index.
*
* @param {IDBObjectStore|IDBIndex} store The object store or index
* @param {IDBKeyRange} [keyRange] The key or key range to query
* @param {string} [direction] The direction of the cursor
* @param {function} done `function(err, data)`
*/
query (store, keyRange, direction, done) {
if (arguments.length === 2) {
done = keyRange;
keyRange = undefined;
direction = 'next';
} else if (arguments.length === 3) {
done = direction;
direction = 'next';
}
var data = [];
var safariPrimaryKeyOffset = 0, safariKeyOffset = 0;
try {
var open = keyRange === undefined ? store.openCursor() : store.openCursor(keyRange, direction);
open.onerror = function () {
done(open.error, data);
};
open.onsuccess = function () {
var cursor = open.result;
if (cursor) {
var key = cursor.key;
var primaryKey = cursor.primaryKey;
if (env.isNative && env.browser.isSafari) {
// BUG: Safari has a bug with compound-key cursors
if (primaryKey instanceof Array) {
primaryKey.splice(0, safariPrimaryKeyOffset);
safariPrimaryKeyOffset += primaryKey.length;
}
if (key instanceof Array) {
key.splice(0, safariKeyOffset);
safariKeyOffset += key.length;
}
}
data.push({
primaryKey: primaryKey,
key: key,
value: cursor.value
});
cursor.continue();
} else {
done(null, data);
}
};
} catch (e) {
done(e, data);
}
},
/**
* Generates a new database name that is unique for this test-run.
* Database names are not re-used in a single test-run, because many native browser implementations
* wait to delete databases until garbage collection occurs. So attempting to re-use a database name
* that is pending deletion will cause runtime errors.
*
* @param {function} done `function(err, dbName)`
*/
generateDatabaseName (done) {
dbNameCounter++;
var dbName = databaseNamePrefix + dbNameCounter + databaseSuffix;
// Remember this database name, so it can be deleted when the test is done
util.currentTest.databases.push(dbName);
// Just in case the database already exists, delete it
var request = env.indexedDB.deleteDatabase(dbName);
request.onsuccess = function () {
done(null, dbName);
};
request.onerror = request.onblocked = function () {
var err;
try {
err = request.error;
console.error(err.message);
} finally {
done(err || 'Unknown Error');
}
};
},
/**
* An asynchronous for-each loop
*
* @param {array} array The array to loop through
*
* @param {function} done Callback function (when the loop is finished or an error occurs)
*
* @param {function} iterator
* The logic for each iteration. Signature is `function(item, index, next)`.
* Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop.
* Or don't call `next` at all to break out of the loop.
*
* If iterator returns an {@link IDBRequest} or {@link IDBTransaction} object,
* then `next` will automatically be bound to the `onsuccess`, `onerror`, `onblocked`, and `oncomplete` events.
*/
asyncForEach (array, done, iterator) {
var i = 0;
next();
function next (err) {
if (err) {
done(err);
} else if (i >= array.length) {
done();
} else if (i < array.length) {
var item = array[i++];
setTimeout(function () {
var nextCalled = false;
// Call the iterator function
var request = iterator(item, i - 1, function (err) {
if (!nextCalled) {
nextCalled = true;
next(err);
}
});
// If it returned an IDBRequest or IDBTransaction, then bind to its events
if (typeof request === 'object') {
request.onsuccess = request.onerror = request.onblocked = request.oncomplete = function () {
if (!nextCalled) {
nextCalled = true;
var err;
try {
err = request.error;
} catch (e) { /* Some browsers throw an error when accessing the error property */ }
next(err);
}
};
}
}, typeof window !== 'undefined' && typeof global === 'undefined' ? 0 : 300);
}
}
},
stubWindowOnerror (stateObj, cb) {
// As Mocha or Sinon are apparently already using window.onerror, we provide the stubbing ourselves
util._onerror = window.onerror;
stateObj.erred = false;
window.onerror = function () {
stateObj.erred = true;
if (cb) {
return cb();
}
util._onerror.apply(window, arguments);
};
},
restoreWindowOnerror () {
window.onerror = util._onerror;
}
};
/**
* A class with instance and prototype properties.
* Used to test the IndexedDB structured cloning algorithm.
*/
function Person (name, age, dob, isMarried) {
name && (this.name = name);
age && (this.age = age);
dob && (this.dob = dob);
isMarried && (this.isMarried = isMarried);
}
Person.prototype.name = '';
Person.prototype.age = 0;
Person.prototype.dob = new Date(1900, 0, 1);
Person.prototype.isMarried = false;
/**
* Creates a pre-defined schema item for use in a test.
*
* @param {IDBTransaction} tx The database upgrade transaction
* @param {string} schemaItem The name of the schema item to create
*/
function createSchemaItem (tx, schemaItem) {
switch (schemaItem) {
case 'out-of-line':
case 'out-of-line-compound':
tx.db.createObjectStore(schemaItem);
break;
case 'out-of-line-generated':
tx.db.createObjectStore(schemaItem, {autoIncrement: true});
break;
case 'inline':
tx.db.createObjectStore(schemaItem, {keyPath: 'id'});
break;
case 'inline-generated':
tx.db.createObjectStore(schemaItem, {keyPath: 'id', autoIncrement: true});
break;
case 'inline-compound':
tx.db.createObjectStore(schemaItem, {keyPath: ['id', 'name']});
break;
case 'dotted':
tx.db.createObjectStore(schemaItem, {keyPath: 'name.first'});
break;
case 'dotted-generated':
tx.db.createObjectStore(schemaItem, {keyPath: 'name.first', autoIncrement: true});
break;
case 'dotted-compound':
tx.db.createObjectStore(schemaItem, {keyPath: ['id', 'name.first', 'name.last']});
break;
case 'inline-index':
createIndex(schemaItem, 'id');
break;
case 'unique-index':
createIndex(schemaItem, 'id', {unique: true});
break;
case 'multi-entry-index':
createIndex(schemaItem, 'id', {multiEntry: true});
break;
case 'unique-multi-entry-index':
createIndex(schemaItem, 'id', {unique: true, multiEntry: true});
break;
case 'dotted-index':
createIndex(schemaItem, 'name.first');
break;
case 'compound-index':
createIndex(schemaItem, ['id', 'name.first', 'name.last']);
break;
case 'compound-index-unique':
createIndex(schemaItem, ['id', 'name.first', 'name.last'], {unique: true});
break;
default:
throw new Error(schemaItem + ' is not one of the pre-defined schema items');
}
// Creates an index on all object stores
function createIndex (name, keyPath, options) {
for (var i = 0; i < tx.db.objectStoreNames.length; i++) {
var store = tx.objectStore(tx.db.objectStoreNames[i]);
store.createIndex(name, keyPath, options);
}
}
}
})();