TypeScript tsconfig.json
아래와 같이
tsconfig.json
을 셋팅하고, 모듈 paths
가 설정된 경우 jest로 테스트할 때 모듈을 찾지 못하는 경우가 있음.{
"compilerOptions" {
"paths": {
"src/*": ["./*"],
"libs/*": ["libs/*"]
}
}
}
Jest jest.config.ts
Moule aliases 를 사용할 경우 Jest도 알 수 있도록 셋팅을 해줘야 함. 당연하게도 TypeScript에서 jest를 가동하려면
ts-jest
@types/jest
모듈 모두 필요import { pathsToModuleNameMapper, GlobalConfigTsJest } from "ts-jest";
import ts from "typescript";
const compilerOptionsPaths = (() => {
const configFileName = ts.findConfigFile(
"../",
ts.sys.fileExists,
"tsconfig.json",
);
if (configFileName) {
const configFile = ts.readConfigFile(configFileName, ts.sys.readFile);
const option = ts.parseJsonConfigFileContent(
configFile.config,
ts.sys,
"./",
);
return option.raw.compilerOptions.paths;
}
return {};
})();
const tsJestConfig: GlobalConfigTsJest = {
"ts-jest": {
tsconfig: "tsconfig.json",
compiler: "typescript",
},
};
const jestSetting = {
setupFiles: ["<rootDir>/.jest/setupEnv.js"],
globals: tsJestConfig,
moduleFileExtensions: ["ts", "tsx", "js", "json"],
roots: ["<rootDir>"],
modulePaths: ["<rootDir"],
moduleNameMapper: pathsToModuleNameMapper(compilerOptionsPaths),
moduleDirectories: ["node_modules", "src"],
modulePathIgnorePatterns: ["dist"],
testRegex: "\\.spec|\\.test\\.ts$",
transform: {
"^.+\\.ts$": "ts-jest",
},
};
export default jestSetting;
여기서,
setupFiles
는 프로젝트 설정 및 테스트 환경설정을 위해 .jest/setupEnv.js
파일을 만들어 둔다. (필요없으면 이 항목 삭제해도 무방)tsconfig.json
의 paths
설정을 가져와서 moduleNameMapper
설정을 추가해줌으로서 끝난다.나머지 Jest 설정은 해당 프로젝트에 맞게 수정하여 사용 가능하다.