Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexedDB testing with Jest & enzyme - ReferenceError: indexedDB is not defined

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.

like image 892
Mateusz Bielak Avatar asked Dec 22 '17 00:12

Mateusz Bielak


2 Answers

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

like image 71
Phillip Thomas Avatar answered Sep 24 '22 22:09

Phillip Thomas


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']
like image 44
Alok Kumar Avatar answered Sep 24 '22 22:09

Alok Kumar