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

Database ID is not unique when extracted to a setup helper file (using Vitest)

themagickoala opened this issue · comments

I've recently migrated from Jest to Vitest to run my tests, but I'm seeing an issue where the db instance seems to be shared across different test suites. I feel like I must be doing something wrong here, but can't quite figure out what!

I've created a minimal reproduction here: https://github.com/themagickoala/msw-data-vitest-pollution

If you run npm run test you can see errors being thrown in the add user handler because a user with the given id already exists. Is there something I'm doing that's against the recommended usage of this library? Or is it a Vitest issue (I wasn't seeing this with Jest)?

Ok, so I've tracked this down, and actually I think this is a bug because Vitest is isolating correctly where Jest was not. Because we're extracting our setup functionality into a helper (in database.ts), the id for the db instance is calculated to be the same in parallel test suites, as callOrder is set on a per-suite basis (and incremented on a per-suite basis), and the call stack is identical for each test.

Thus, I guess this issue has become: find a way to generate the db id while taking the test suite into account.

commented

I'm running into the same issue with Vitest. If I'm understanding correctly, it is synchronizing database events between parallel unit tests in the same way as it would synchronize database events across open tabs (as described in #66).

I've designed my unit tests to run in isolation by creating a database per suite, but the synchronization is breaking that isolation and causing tests to fail.

The proposed PR does fix the issue, but adding randomization to the database id by default would break synchronization in cases when it is desired. Maybe giving developers a way to opt in or out of the synchronization using an argument to the factory function would work?

In the meantime, this temporary workaround in my code fixes it for me -

const randomizeDbIds = () => {
  if (!import.meta.env.RUNNING_VITEST) return;

  // @ts-expect-error - Overwriting private method from  @msw/data
  Database.prototype.generateId = () => randUuid();
};

Released: v0.13.1 🎉

This has been released in v0.13.1!

Make sure to always update to the latest version (npm i @mswjs/data@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.

@kettanaito was this released correctly? I just tried both 0.13.1 and 0.14.0 and the issue still persists. I can't see related changes in built Database.js module