jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.29k stars 353 forks source link

Ideas on workaround of unexpected jest error? #174

Closed ZYinMD closed 4 years ago

ZYinMD commented 4 years ago

I encountered an unexpected error in my unit tests that has nothing to do with IndexedDB. My question may be better suited for the jest repo or stackoverflow, but I'll ask here in case future users search for it.

In a webpack bundled react project, I have a failed jest test like this:

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

// b.js
import { dbConnection } from './a';
function notEvenCalled() {
  dbConnection.then(db => { /* not doing anything */ });
}
export const foo = 1;

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

// d.js
import { bar } from './c';
export function innocentFunction() {
  return 'I am innocent';
}
function notEvenCalled() {
  console.log(innocentFunction(), bar);
}

// d.test.js
import { innocentFunction } from './d';
test('why', () => {
  expect(innocentFunction()).toBe('I am innocent'); // 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.

One simple workaround is to put the function-to-be-tested into its own file where there's no other import, but I'm curious if people have other solutions.

ZYinMD commented 4 years ago

Closing as this issue is better suited elsewhere.