dumbmatter / fakeIndexedDB

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

Reset auto-incrementing after each test #37

Closed milica closed 4 years ago

milica commented 4 years ago

Hi there! First, the library is awesome, great work :)

And now my question, is it possible to reset the db after each test in a way that auto-increment ids begin from 1? The problem that I have is that I can't write independent tests for stores with auto-incrementing ids (I'm testing those autogenerated values as well, I can explain why I do this if you're interested). For example, in one test I push several items to a store and then ids are created like 1,2,3 and then I continue with another test which pushes to that same store (previously cleared of course) but ids begin from 4 (unless this test is run in isolation). Can you suggest on how to completely reset the db so it affects this global counter or is there any kind of workaround for this issue? Thanks!

dumbmatter commented 4 years ago

You're right that just calling IDBObjectStore.clear does not reset the counter, but that's a good thing because it matches how browsers behave.

You have a couple options to reset the counter...

  1. Delete the database and recreate it between tests - this is probably the best solution, because it'll continue to work if you ever want to run your tests in a browser

  2. Reset the counter within fake-indexeddb by running db.transaction('test').objectStore('test')._rawObjectStore.keyGenerator.num = 0 where db is a database connection. Or without a database connection, you can do fakeIndexedDB._databases.get("foo").rawObjectStores.get("test").keyGenerator.num = 0 for a database named "foo" and an object store named "test". I can't guarantee this will work forever because it's an internal API and really it should be private, but I don't have any plan to change it.

milica commented 4 years ago

Ok, got it, completely understand. I'll try it out. Thanks a lot for the quick response!