shelfio / jest-mongodb

Jest preset for MongoDB in-memory server
MIT License
591 stars 83 forks source link

use rootDir instead of cwd for globalConfig location #389

Closed ajwootto closed 1 year ago

ajwootto commented 1 year ago

Using cwd to determine the location to put the globalConfig.json causes a conflict between parallel test runs in a monorepo when Jest is invoked from the root of the repository and has a particular jest.config file specified.

This is how tools like Nx invoke tests. Commands are run from the root of the repo and if I do something like nx run-many --target=test --projects=project1,project2 this results in two separate jest commands being executed at the same time. Each command has the same cwd value (the repository root) but is pointed at a different jest.config file which specified which test files to run. This causes the runs to conflict, because when one of them finishes it will delete the globalConfig.json file which the other one then attempts to read for any test files it has left to execute.

Instead, switch to using the rootDir property of the jest environment config, which defaults to the location of the jest.config file currently in use for this test run. https://jestjs.io/docs/configuration#rootdir-string

harazdovskiy commented 1 year ago

Hi @ajwootto, looks like a valid example, thanks for contributing!

gierschv commented 1 year ago

I upgraded from 4.1.2 to 4.1.3 and this patch breaks using jest with the projects configuration option in a regular monorepo, without any extra tools.

e.g. at the root of the monorepo I have:

module.exports = {
  projects: ['<rootDir>/packages/*'],
};

In one package packages/api/jest.config.js, I use the @shelf/jest-mongodb preset.

Once run jest at the root of the monorepo:

$ jest

 FAIL  packages/api/test/api/controllers/xxx.js
  ● Test suite failed to run

    ENOENT: no such file or directory, open '/monorepo/packages/api/globalConfig.json'

      at MongoEnvironment.setup (../../node_modules/.pnpm/@shelf+jest-mongodb@4.1.3_b3jolve2gmpnfixk5q25zduirq/node_modules/@shelf/jest-mongodb/lib/environment.js:23:58)
Grmiade commented 1 year ago

We have the same issue as @gierschv. Any workaround?

ajwootto commented 1 year ago

@gierschv @Grmiade sorry about that, I just opened a PR to try and fix this problem for your setup.