Ts-jest: Issue with rewire "Cannot find module"

Created on 13 Mar 2019  路  14Comments  路  Source: kulshekhar/ts-jest

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
Help Wanted

Most helpful comment

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.

All 14 comments

Same here

+1

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

+1

+1

+1

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

bump

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

+1

+1

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.

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

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Slessi picture Slessi  路  3Comments

artola picture artola  路  3Comments

stangerjm picture stangerjm  路  4Comments

mikeyakymenko picture mikeyakymenko  路  3Comments

stephenotalora picture stephenotalora  路  3Comments