Created
May 10, 2024 08:59
-
-
Save akwodkiewicz/a3b7fee4deabd203fb866c48faeb5813 to your computer and use it in GitHub Desktop.
Custom Jest resolver to solve "dual state" issues with self-referencing and subpath imports in TypeScript projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This resolver forces Jest to look at a *custom* `"jest"` condition in `package.json#exports`. | |
* | |
* Whenever you use self-referencing imports or subpath imports in the source code (or tests) | |
* the default behaviour of Jest is to go to the package's manifest for information, and resolve | |
* the import by choosing one of the conditions that are used by Node ("node", "default", etc.). | |
* | |
* The issue is that "node"/"default" usually points to transpiled `.js` files, whereas if you decide to | |
* run the tests on the `.ts` source code (with the help of a transformer such as ts-jest or @swc/jest), | |
* you need Jest to **only** load the `.ts` files. Otherwise, you end up with duplicated classes, | |
* variables -- "duplicated state" in general -- which causes all issues with mocks and even the test correctness. | |
* | |
* The paths defined under the "jest" conditional export should point to the .ts source code. | |
* | |
* Tried to leverage the existing "types" conditional export to elliminate the need for | |
* an additional entry, but it does not work. It looks as if `"types"` entry was explicitly banned | |
* by the Jest runtime from being a valid resolver condition. | |
* | |
* You *will not* have this problem if your code only uses relative imports and/or TypeScript path aliases | |
* (which are actually resolved to relative imports during the test execution). | |
*/ | |
module.exports = (path, options) => { | |
return options.defaultResolver(path, { | |
...options, | |
conditions: ['jest'].concat(options.conditions), | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment