I'm looking for help with unit tests for my app, where I'm using indexedDB. Before I implemented indexedDB functionality, tests were correct. But now, for all of them I see one error:
ReferenceError: indexedDB is not defined
Can someone give me an advice how to get rid of that error? I was searching information, and trying different ways to mock window, or indexedDB, but with no result.
This issue is due to Dexie expecting window.indexedDB to be defined, this is not the case when running in a headless mode (using Jest) that does not have a true DOM or window scope.
Found a solution deep in the Dexie git issues which suggests:
const Dexie = require('dexie')
Dexie.dependencies.indexedDB = require('fake-indexeddb')
Dexie.dependencies.IDBKeyRange = require('fake-indexeddb/lib/FDBKeyRange')
We have also had success with:
import Dexie from 'dexie';
import indexedDB from 'fake-indexeddb';
Dexie.dependencies.indexedDB = indexedDB;
Link to the original issue: https://github.com/dfahlander/Dexie.js/issues/495
Or according to the documentation, you can provide the indexedDB option like:
import Dexie from 'dexie';
import indexedDB from 'fake-indexeddb';
var db = new Dexie("MyDatabase", { indexedDB: indexedDB });
Link to documentation: http://dexie.org/docs/Dexie/Dexie
If You are using jest and enzyme for testing indexdb or you are using dexie which is a indexDB wrapper which is also used for implementing indexDB api you have to just add these three lines in you global-test.js file .
const Dexie = require('dexie');
Dexie.dependencies.indexedDB = require('fake-indexeddb');
Dexie.dependencies.IDBKeyRange = require('fake-indexeddb/lib/FDBKeyRange');
Now you have to provide this file to jest, show that it can use fake-indexddb instead of original indexDB.
setupFiles: ['<rootDir>/src/test/globals-test.ts']
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With