Skip to content

Instantly share code, notes, and snippets.

@itssimmons
Last active January 20, 2022 00:02
Show Gist options
  • Save itssimmons/a2911769ef6f06b86137a3cf4f817a74 to your computer and use it in GitHub Desktop.
Save itssimmons/a2911769ef6f06b86137a3cf4f817a74 to your computer and use it in GitHub Desktop.
Simple configuration to set up jest and typescript with its custom paths 📁🧪
const { pathsToModuleNameMapper } = require('ts-jest');
//const { pathsToModuleNameMapper } = require('ts-jest/utils'); // also you can do like this, but jest recommends use one above
const { compilerOptions } = require('./tsconfig.json');
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
coverageDirectory: './coverage',
testMatch: [ "**/?(*.)+(test).ts" ],
resetMocks: true,
clearMocks: true,
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/src' })
}
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"strict": true,
"declaration": true,
"noImplicitAny": true,
"removeComments": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"traceResolution": true,
"strictPropertyInitialization": false,
"declarationDir": "./lib",
"outDir": "./dist",
"rootDir": ".",
"baseUrl": "src",
"paths": {
"@/*": [ "./*" ],
"@models": [ "interfaces/barrel.ts" ]
},
},
"include": [ "src/**/*" ],
"exclude": [ "node_modules" ]
}
@itssimmons
Copy link
Author

Good practice?

I actually don't know if custom paths are good practices, because you want to test ts files, not js files. And tests are usually excluded in the tsconfig.json, so I think that the custom paths should not be used in the tests files. That's my assumption.

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": { "@/*": [ "./*" ] }
  },
  "include": [ "src/**/*" ],
  "exclude": [ 
    "node_modules", 
    "**/*.test.ts", 
    "**/*.spec.ts" 
  ]
}

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