Resolve paths dynamically based on directory where test (or tested files) is located in Jest

18 views Asked by At

I am working on setting and configuring jest test in my React code. If very simplified historically I have a folder structure like this:

node_modules
jest.config.js
common
  commonFunc.js
abc
  someFuncA.js
  someFuncA.test.js
xyz
  someFuncB.js
  someFuncB.test.js

So the webpack is configured to resolve paths this way:

// If import is ocured in abc directory:
import someFuncA from 'specific/someFuncA' --> import someFuncA from 'abc/someFuncA'
// If import is ocured in xyz directory:
import someFuncB from 'specific/someFuncB' --> import someFuncB from 'xyz/someFuncB'

So the import path is dynamically resolved based on file location (specific is replaced with abc or xyz). Now I need to apply a similar approach in my Jest tests and configure it to resolve imports similar way as the webpack does.

However, I am not able to implement it.

I tried to adjust Jest moduleNameMapper config like:

moduleNameMapper: {
  '^specific(.*)$': '<rootDir>/abc$1', // but how to resolve xyz properly?
},

and I also tried to play with jest resolver option, but looks like the test file location path is not accessible from resolver, and I was not able to pass it manually there in some way. And without knowing if the current test is executed from abc or xyz folder, I don't see how resolver could be helpfull here.

Would appreciate your help!

0

There are 0 answers