mswjs / data

Data modeling and relation library for testing JavaScript applications.

Home Page:https://npm.im/@mswjs/data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

add the ability to have some "undroppable" initial data

cloud-walker opened this issue · comments

In my current custom fake data implementation, I have the ability to seed the database with some initial data, that will remain untouched across drops:

const initialData: DatabaseData = Object.freeze({
  todos: [...],
  users: [...],
})

let data = initialData

/**
 * We need this mechanism as we need to simulate a "database"
 * reset for every test run in order to maintain a clean
 * "database" state for every test.
 *
 * @note it is crucial to not mutate the internal structure of
 * the initialData, in order to achieve this.
 */
export const resetData = () => {
  data = initialData
}

export const getData = () => data

export const setData = (transformer: (data: DatabaseData) => DatabaseData) => {
  data = transformer(data)
}

Currently using @mswjs/data, if I reset the db with drop(db), I lose ALL the data, and I think is not practical to reseed the data on each test 🤔

Hey, @cloud-walker.

Please note that drop() is not meant for resetting the database state. It's designed to drop all the entities in the database.

If you wish to reset the state, consider combining drop with your seeding function:

import { drop } from '@mswjs/data'

function seed(db) {
  db.user.create({...})
  db.todo.create({...})
}

function resetDb(db) {
  drop(db)
  seed(db)
}

Would this approach work for your use case?

We've also discussed the reset API here, where the following API was suggested:

import { factory, snapshot } from '@mswjs/data'

const db = factory({...})
// seed your db...
db.user.create(...)

// Take the snapshot of database entities
// in this point of time.
const reset = snapshot(db)

// change the entities...
db.user.update(...)
db.todo.create(...)

// Reset to the exact state when
// the snapshot was taken.
reset()

There's been no investigating whether such API is possible with the current architecture, but if we ever adopt a reset API, it'd look similar to this.

Thats how I solved the issue with my current @mswjs/data experiment. But I think it's a waste of computation to do a reseed afterEach test.

BTW the snapshot proposal could solve the use case!

Closing this in favor of #86.