Issue with rewire "Cannot find module"
See original GitHub issueIssue
I’m unable to use rewire with ts-jest, it seems to works with .js
files, but it does not with .ts
files as supposed to.
Expected behavior
Being able to rewire a module with jest with ts-jest.
Debug log:
# content of ts-jest.log :
{"context":{"allowJs":false,"logLevel":20,"namespace":"jest-preset","package":"ts-jest","version":"24.0.0"},"message":"creating jest presets not handling JavaScript files","sequence":1,"time":"2019-03-13T22:22:59.064Z"}
{"context":{"logLevel":20,"namespace":"Importer","package":"ts-jest","version":"24.0.0"},"message":"creating Importer singleton","sequence":2,"time":"2019-03-13T22:23:00.323Z"}
{"context":{"allowJs":false,"logLevel":20,"namespace":"jest-preset","package":"ts-jest","version":"24.0.0"},"message":"creating jest presets not handling JavaScript files","sequence":3,"time":"2019-03-13T22:23:00.326Z"}
{"context":{"actualVersion":"24.5.0","expectedVersion":">=24 <25","logLevel":20,"namespace":"versions","package":"ts-jest","version":"24.0.0"},"message":"checking version of jest: OK","sequence":4,"time":"2019-03-13T22:23:00.327Z"}
{"context":{"baseOptions":{},"logLevel":20,"namespace":"jest-transformer","package":"ts-jest","transformerId":1,"version":"24.0.0"},"message":"created new transformer","sequence":5,"time":"2019-03-13T22:23:00.327Z"}
{"context":{"fileName":"/Users/david/dev/ts-test-jest/tests/imported.test.ts","logLevel":20,"namespace":"jest-transformer","package":"ts-jest","transformOptions":{"config":{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/private/var/folders/7n/fgd5_hhn6yb0hl6p9hg7s77w0000gn/T/jest_dx","clearMocks":false,"coveragePathIgnorePatterns":["/node_modules/"],"cwd":"/Users/david/dev/ts-test-jest","dependencyExtractor":null,"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"computeSha1":false,"providesModuleNodeModules":[],"throwOnModuleCollision":false},"moduleDirectories":["node_modules"],"moduleFileExtensions":["js","json","jsx","ts","tsx","node"],"moduleNameMapper":{},"modulePathIgnorePatterns":[],"name":"d7f7a374ad658fc3075cd461f89bbebe","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/Users/david/dev/ts-test-jest","roots":["/Users/david/dev/ts-test-jest"],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"snapshotSerializers":[],"testEnvironment":"/Users/david/dev/ts-test-jest/node_modules/jest-environment-jsdom/build/index.js","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],"testPathIgnorePatterns":["/node_modules/"],"testRegex":[],"testRunner":"/Users/david/dev/ts-test-jest/node_modules/jest-jasmine2/build/index.js","testURL":"http://localhost","timers":"real","transform":[["^.+\\.tsx?$","/Users/david/dev/ts-test-jest/node_modules/ts-jest/dist/index.js"]],"transformIgnorePatterns":["/node_modules/"],"watchPathIgnorePatterns":[]},"instrument":false,"rootDir":"/Users/david/dev/ts-test-jest"},"transformerId":1,"version":"24.0.0"},"message":"computing cache key for /Users/david/dev/ts-test-jest/tests/imported.test.ts","sequence":6,"time":"2019-03-13T22:23:00.328Z"}
{"context":{"logLevel":30,"namespace":"jest-transformer","package":"ts-jest","transformerId":1,"version":"24.0.0"},"message":"no matching config-set found, creating a new one","sequence":7,"time":"2019-03-13T22:23:00.328Z"}
{"context":{"config":{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/private/var/folders/7n/fgd5_hhn6yb0hl6p9hg7s77w0000gn/T/jest_dx","clearMocks":false,"coveragePathIgnorePatterns":["/node_modules/"],"cwd":"/Users/david/dev/ts-test-jest","dependencyExtractor":null,"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"computeSha1":false,"providesModuleNodeModules":[],"throwOnModuleCollision":false},"moduleDirectories":["node_modules"],"moduleFileExtensions":["js","json","jsx","ts","tsx","node"],"moduleNameMapper":{},"modulePathIgnorePatterns":[],"name":"d7f7a374ad658fc3075cd461f89bbebe","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/Users/david/dev/ts-test-jest","roots":["/Users/david/dev/ts-test-jest"],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"snapshotSerializers":[],"testEnvironment":"/Users/david/dev/ts-test-jest/node_modules/jest-environment-jsdom/build/index.js","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],"testPathIgnorePatterns":["/node_modules/"],"testRegex":[],"testRunner":"/Users/david/dev/ts-test-jest/node_modules/jest-jasmine2/build/index.js","testURL":"http://localhost","timers":"real","transform":[["^.+\\.tsx?$","/Users/david/dev/ts-test-jest/node_modules/ts-jest/dist/index.js"]],"transformIgnorePatterns":["/node_modules/"],"watchPathIgnorePatterns":[]},"logLevel":20,"namespace":"backports","package":"ts-jest","transformerId":1,"version":"24.0.0"},"message":"backporting config","sequence":8,"time":"2019-03-13T22:23:00.329Z"}
{"context":{"jestConfig":{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/private/var/folders/7n/fgd5_hhn6yb0hl6p9hg7s77w0000gn/T/jest_dx","clearMocks":false,"coveragePathIgnorePatterns":["/node_modules/"],"cwd":"/Users/david/dev/ts-test-jest","dependencyExtractor":null,"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{"ts-jest":{}},"haste":{"computeSha1":false,"providesModuleNodeModules":[],"throwOnModuleCollision":false},"moduleDirectories":["node_modules"],"moduleFileExtensions":["js","json","jsx","ts","tsx","node"],"moduleNameMapper":{},"modulePathIgnorePatterns":[],"name":"d7f7a374ad658fc3075cd461f89bbebe","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/Users/david/dev/ts-test-jest","roots":["/Users/david/dev/ts-test-jest"],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"snapshotSerializers":[],"testEnvironment":"/Users/david/dev/ts-test-jest/node_modules/jest-environment-jsdom/build/index.js","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],"testPathIgnorePatterns":["/node_modules/"],"testRegex":[],"testRunner":"/Users/david/dev/ts-test-jest/node_modules/jest-jasmine2/build/index.js","testURL":"http://localhost","timers":"real","transform":[["^.+\\.tsx?$","/Users/david/dev/ts-test-jest/node_modules/ts-jest/dist/index.js"]],"transformIgnorePatterns":["/node_modules/"],"watchPathIgnorePatterns":[]},"logLevel":20,"namespace":"config","package":"ts-jest","transformerId":1,"version":"24.0.0"},"message":"normalized jest config","sequence":9,"time":"2019-03-13T22:23:00.329Z"}
{"context":{"logLevel":20,"namespace":"config","package":"ts-jest","transformerId":1,"tsJestConfig":{"compiler":"typescript","diagnostics":{"ignoreCodes":[6059,18002,18003],"pretty":true,"throws":true},"isolatedModules":false,"transformers":[],"tsConfig":{"kind":"file"}},"version":"24.0.0"},"message":"normalized ts-jest config","sequence":10,"time":"2019-03-13T22:23:00.330Z"}
{"context":{"logLevel":20,"namespace":"config","package":"ts-jest","transformerId":1,"version":"24.0.0"},"message":"babel is disabled","sequence":11,"time":"2019-03-13T22:23:00.331Z"}
{"context":{"logLevel":20,"namespace":"Importer","package":"ts-jest","requireResult":{"exists":true,"given":"typescript","path":"/Users/david/dev/ts-test-jest/node_modules/typescript/lib/typescript.js"},"version":"24.0.0"},"message":"loaded module typescript","sequence":12,"time":"2019-03-13T22:23:00.598Z"}
{"context":{"logLevel":20,"namespace":"Importer","package":"ts-jest","version":"24.0.0"},"message":"patching typescript","sequence":13,"time":"2019-03-13T22:23:00.598Z"}
{"context":{"actualVersion":"3.3.3333","expectedVersion":">=2.7 <4","logLevel":20,"namespace":"versions","package":"ts-jest","version":"24.0.0"},"message":"checking version of typescript: OK","sequence":14,"time":"2019-03-13T22:23:00.599Z"}
{"context":{"logLevel":20,"namespace":"config","package":"ts-jest","transformerId":1,"tsConfigFileName":"/Users/david/dev/ts-test-jest/tsconfig.json","version":"24.0.0"},"message":"readTsConfig(): reading /Users/david/dev/ts-test-jest/tsconfig.json","sequence":15,"time":"2019-03-13T22:23:00.599Z"}
{"context":{"logLevel":20,"namespace":"config","package":"ts-jest","transformerId":1,"tsconfig":{"input":{"compilerOptions":{"allowSyntheticDefaultImports":true,"baseUrl":".","esModuleInterop":true,"jsx":"react","module":"es2015","moduleResolution":"node","noImplicitAny":false,"outDir":"build/","paths":{"*":["*","node_modules/*"]},"skipLibCheck":true,"sourceMap":true,"target":"es5"},"include":["common"]},"resolved":{"compileOnSave":false,"configFileSpecs":{"excludeSpecs":["build/"],"includeSpecs":["common"],"validatedExcludeSpecs":["build/"],"validatedIncludeSpecs":["common"],"wildcardDirectories":{"/Users/david/dev/ts-test-jest/common":1}},"errors":[],"fileNames":["/Users/david/dev/ts-test-jest/common/imported.ts"],"options":{"allowSyntheticDefaultImports":true,"baseUrl":"/Users/david/dev/ts-test-jest","configFilePath":"/Users/david/dev/ts-test-jest/tsconfig.json","declaration":false,"esModuleInterop":true,"inlineSourceMap":false,"inlineSources":true,"jsx":2,"module":1,"moduleResolution":2,"noEmit":false,"noImplicitAny":false,"outDir":"$$ts-jest$$","paths":{"*":["*","node_modules/*"]},"removeComments":false,"skipLibCheck":true,"sourceMap":true,"target":1},"raw":{"compileOnSave":false,"compilerOptions":{"allowSyntheticDefaultImports":true,"baseUrl":".","esModuleInterop":true,"jsx":"react","module":"es2015","moduleResolution":"node","noImplicitAny":false,"outDir":"build/","paths":{"*":["*","node_modules/*"]},"skipLibCheck":true,"sourceMap":true,"target":"es5"},"include":["common"]},"typeAcquisition":{"enable":false,"exclude":[],"include":[]},"wildcardDirectories":{"/Users/david/dev/ts-test-jest/common":1}}},"version":"24.0.0"},"message":"normalized typescript config","sequence":16,"time":"2019-03-13T22:23:00.614Z"}
{"context":{"fileName":"/Users/david/dev/ts-test-jest/common/imported.ts","logLevel":20,"namespace":"jest-transformer","package":"ts-jest","transformOptions":{"config":{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/private/var/folders/7n/fgd5_hhn6yb0hl6p9hg7s77w0000gn/T/jest_dx","clearMocks":false,"coveragePathIgnorePatterns":["/node_modules/"],"cwd":"/Users/david/dev/ts-test-jest","dependencyExtractor":null,"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"computeSha1":false,"providesModuleNodeModules":[],"throwOnModuleCollision":false},"moduleDirectories":["node_modules"],"moduleFileExtensions":["js","json","jsx","ts","tsx","node"],"moduleNameMapper":{},"modulePathIgnorePatterns":[],"name":"d7f7a374ad658fc3075cd461f89bbebe","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/Users/david/dev/ts-test-jest","roots":["/Users/david/dev/ts-test-jest"],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"snapshotSerializers":[],"testEnvironment":"/Users/david/dev/ts-test-jest/node_modules/jest-environment-jsdom/build/index.js","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],"testPathIgnorePatterns":["/node_modules/"],"testRegex":[],"testRunner":"/Users/david/dev/ts-test-jest/node_modules/jest-jasmine2/build/index.js","testURL":"http://localhost","timers":"real","transform":[["^.+\\.tsx?$","/Users/david/dev/ts-test-jest/node_modules/ts-jest/dist/index.js"]],"transformIgnorePatterns":["/node_modules/"],"watchPathIgnorePatterns":[]},"instrument":false,"rootDir":"/Users/david/dev/ts-test-jest"},"transformerId":1,"version":"24.0.0"},"message":"computing cache key for /Users/david/dev/ts-test-jest/common/imported.ts","sequence":17,"time":"2019-03-13T22:23:00.617Z"}
Minimal repo
https://github.com/DavidBabel/test-jest-rewire-typescript
git clone https://github.com/DavidBabel/test-jest-rewire-typescript
yarn & jest
Issue Analytics
- State:
- Created 5 years ago
- Reactions:13
- Comments:17
Top Results From Across the Web
Cannot find module "module" - Rewire.js - Stack Overflow
var Module = require("module"), I know there is a Webpack Rewire plugin, but when I use it, I have the same problem as...
Read more >rewire - npm
During the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see #62). Other ......
Read more >react-app-rewired cannot find modules : r/reactjs - Reddit
I'm using react-app-rewire-alias` to solve the issue: The following changes ... [0] Module not found: Can't resolve '@Shared/ChannelName' in ...
Read more >Issue with rewire "Cannot find module" - - Bountysource
I'm unable to use rewire with ts-jest, it seems to works with .js files, but it does not with .ts files as supposed...
Read more >How to spy on your required modules | Toucan Toco
... start testing your project, you quickly run into problems and you can't find any documentation. ... A simple caseLet's use a spyUsing...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I had the same issue on using
rewire
withts-jest
on Node.js and found a solution.Solution
Use
ts-node
alongsidets-jest
.Example:
Install
ts-node
.Rewrite
package.json
.Run test as usual.
And everything goes well!
Explanation
rewire
usesmodule
module(can be used byrequire('module')
), whichts-jest
does not wrap. Therefore,rewire
resolves the module you importing without typescript functionality, only searching for the file with.js
extension. This results inCannot find module
error since the target*.js
file does not exist.ts-node
hooks the node.js’s native module resolution functionality so we can resolve module with.ts
extension withmodule
module, whichrewire
relies on.-O '{\"module\":\"commonjs\"}'
option is needed only if you don’t have the same configuration in yourtsconfig.json
.Just want to leave a comment here in case anybody else using WebStorm with a Jest run configuration happens to be looking for a fix.
I can confirm that @grainrigi’s solution of adding
ts-node
to the script works. However, a Jest run configuration in WebStorm needs to be resolved separately. You could, of course, create a npm run configuration and simply run your test script. However, you lose the nice UI for test results that the IDE provides (even if you use the--coverage
flag, which is better but still not as clean in my opinion).Fortunately, you can simply add
--require ts-node/register
to the “Node options” in your configuration and this should solve the problem there.I suspect this would also work for IntelliJ, but haven’t tested it personally.