dumbmatter / fakeIndexedDB

A pure JS in-memory implementation of the IndexedDB API
Apache License 2.0
585 stars 70 forks source link

How to deal with jest necessarily traversing into IndexedDB related files #42

Closed ZYinMD closed 4 years ago

ZYinMD commented 4 years ago

demo repo: https://github.com/ZYinMD/jest-indexeddb-undefined-demo

I encountered an "indexeddb is not defined" issue in jest with a create-react-app project. I tried using this package to fix it, but had no luck. Can someone shed some light?

// a.js
import { openDB } from "idb";
export const dbConnection = openDB("myDB", 1);

// b.js
import { dbConnection } from "./a";
export const foo = 1;
export function doSomethingWithDB() {
  dbConnection.then((db) => {
    //...
  });
}

// c.js
import { foo } from "./b";
export const bar = foo + 1;

// d.js
import { bar } from "./c";
export function notEvenCalled() {
  return sum(bar, 100);
}
export function sum(a, b) {
  return a + b;
}

// d.test.js
import { sum } from "./d";
test("why", () => {
  expect(sum(1, 1)).toBe(2); // fail!! indexeddb is not defined.
});

I think it's because jest traverses all files that are connected to the test file via import/export, and also all files connected to those files, and so on.

Is there an easy fix for things like this?

dumbmatter commented 4 years ago

Possibly using real ES modules rather than compiling them to CommonJS would help it be smart enough not to execute that code containing indexeddb, but I'm not sure. If not, then your only options would be to further decouple the functions into separate files, or to mock indexeddb. You could use fake-indexeddb for the latter purpose, like described in the README here. It's kind of overkill if you're not actually testing IndexedDB, but it would work.

ZYinMD commented 4 years ago

Thanks! I tried following the README and set setupFiles: ['fake-indexeddb/auto'] in jest.config.js, it works in my simple demo project, but doesn't work in create-react-app project (test still fails). Is there some other settings I could do?