Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with rewire "Cannot find module" #1029

Closed
DavidBabel opened this issue Mar 13, 2019 · 18 comments
Closed

Issue with rewire "Cannot find module" #1029

DavidBabel opened this issue Mar 13, 2019 · 18 comments

Comments

@DavidBabel
Copy link

Issue

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
# 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
@dortamiguel
Copy link

Same here

@Splash34
Copy link

+1

@ykravv
Copy link

ykravv commented Jun 5, 2019

Any ideas about workaround here? Seems rewire just readFileSync for source code, and it's impossible to get any transformations there with ts-jest

@ohroy
Copy link

ohroy commented Jul 1, 2019

+1

2 similar comments
@phavaha1
Copy link

+1

@harperj1029
Copy link

+1

@ahnpnl
Copy link
Collaborator

ahnpnl commented Jan 1, 2020

I think this might be related to jest and rewire. I've googled and found some posts that there is a babel plugin for this. Look like ts-jest cannot do anything in this case

@collinalexbell
Copy link

bump

@DavidBabel
Copy link
Author

Well, if you use typescript, you do not want to rely to babel.

@kato1628
Copy link

+1

1 similar comment
@mrdulin
Copy link

mrdulin commented Mar 20, 2020

+1

@grainrigi
Copy link

grainrigi commented Apr 7, 2020

I had the same issue on using rewire with ts-jest on Node.js and found a solution.

Solution

Use ts-node alongside ts-jest.

Example:

Install ts-node.

$ npm i -D ts-node

Rewrite package.json.

  "scripts": {
    ...
-   "test": "jest",
+   "test": "ts-node -O '{\"module\":\"commonjs\"}' node_modules/jest/bin/jest.js",
    ...
  },

Run test as usual.

$ npm t

And everything goes well!

Explanation

rewire uses module module(can be used by require('module')), which ts-jest does not wrap.
Therefore, rewire resolves the module you importing without typescript functionality, only searching for the file with .js extension.
This results in Cannot 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 with module module, which rewire relies on.
-O '{\"module\":\"commonjs\"}' option is needed only if you don't have the same configuration in your tsconfig.json.

@ahnpnl
Copy link
Collaborator

ahnpnl commented Apr 28, 2020

Hi guys, I will close this as ts-jest can't do anything since rewire requires a path to js file and ts-jest is just a transformer which delivers codes to jest so jest can execute. You can use the above workaround or following this blog post https://weekly.elfitz.com/2018/10/17/using-rewire-with-typescript-jest/

In general, rewire requires a physical js file on disk, that's why when it tries to execute and there is no js file on disk, it throws "Cannot find module"

Also if you have any ideas to fix this issue for ts-jest, feel free to open PR

@ahnpnl ahnpnl closed this as completed Apr 28, 2020
@TheJizel
Copy link

TheJizel commented Jul 8, 2020

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.

@souvikhazra1
Copy link

@grainrigi and @TheJizel both of you are life-saver.

@ksw25
Copy link

ksw25 commented Mar 2, 2022

I am getting “cannot find module” even for a js file. Please help!!

@DHOscar
Copy link

DHOscar commented Mar 16, 2022

A small add on for those who is searching it like me. If you want to rewire a private method of a export class, here is the trick: https://stackoverflow.com/a/67741151/2450847.

@LeonhWolf
Copy link

Just in case anyone also has this problem: I kept getting an error
SyntaxError: Unexpected token ' in JSON at position 0
when running the script.
Rewriting it to this fixed it for me:

ts-node -O \"{\\\"module\\\":\\\"commonjs\\\"}\" node_modules/jest/bin/jest.js

This was not my idea. See here: https://github.com/TypeStrong/ts-node/issues/313#issuecomment-741249846

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests