沙哑的可以解决tsconfig.ts的路径
我正在使用开玩笑来进行单元测试,并且在我的tsconfig.json中有自定义路径
,它在本地罚款。
但是,当我尝试通过赫斯基和绒毛阶段进行更改时,它会犯“找不到测试文件”或“无法解决 @core/..”
我们必须将Husky的自定义配置用于允许亲戚穿越沙哑的道路?
我的tsconfig.json:
{
"ts-node": {
"transpileOnly": true,
"require": [ "typescript-transform-paths/register" ]
},
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDirs": ["./src", "./build"],
"baseUrl": "src",
"paths": {
"@core/*": ["core/*"],
"@api/*": ["api/*"]
},
"plugins": [
{ "transform": "typescript-transform-paths" },
{ "transform": "typescript-transform-paths", "afterDeclarations": true }
],
"resolveJsonModule": true,
"declaration": true,
"outDir": "./build",
"importHelpers": true,
"importsNotUsedAsValues": "remove",
"noEmitOnError": true,
"declarationDir": "build/@types",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"allowUnusedLabels": true,
"allowUnreachableCode": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts", ".husky/**/*"],
"exclude": ["node_modules", ".vscode"]
}
我的jest.config.ts文件:
// For a detailed explanation regarding each configuration property and type check, visit:
// https://jestjs.io/docs/configuration
// eslint-disable-next-line import/no-extraneous-dependencies
import { pathsToModuleNameMapper } from "ts-jest/dist";
import { compilerOptions } from "./tsconfig.json";
export default {
// All imported modules in your tests should be mocked automatically
automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\ssoylu\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["<rootDir>/**/*.ts"],
// The directory where Jest should output its coverage files
coverageDirectory: "tests/coverage",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ["/tests/"],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["json", "text", "lcov", "clover"],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
errorOnDeprecated: true,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
maxWorkers: "10%",
// An array of directory names to be searched recursively up from the requiring module's location
moduleDirectories: ["src", "node_modules"],
// An array of file extensions your modules use
moduleFileExtensions: ["js", "mjs", "ts", "tsx", "json"],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "ts-jest",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
resetMocks: true,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
rootDir: "./tests",
// A list of paths to directories that Jest should use to search for files in
// roots: ["tests", "src"],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ["**/launcher.test.ts?(x)"],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
I'm using Jest to make my unit tests and I have custom paths
in my tsconfig.json which works all fines in local.
But when I try to commit my changes through husky and lint-staged, it makes errors like "can't find test files" or "can't resolve @core/.."
Do we have to make a custom config of husky to allows relatives paths through husky ?
my tsconfig.json :
{
"ts-node": {
"transpileOnly": true,
"require": [ "typescript-transform-paths/register" ]
},
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDirs": ["./src", "./build"],
"baseUrl": "src",
"paths": {
"@core/*": ["core/*"],
"@api/*": ["api/*"]
},
"plugins": [
{ "transform": "typescript-transform-paths" },
{ "transform": "typescript-transform-paths", "afterDeclarations": true }
],
"resolveJsonModule": true,
"declaration": true,
"outDir": "./build",
"importHelpers": true,
"importsNotUsedAsValues": "remove",
"noEmitOnError": true,
"declarationDir": "build/@types",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"allowUnusedLabels": true,
"allowUnreachableCode": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts", ".husky/**/*"],
"exclude": ["node_modules", ".vscode"]
}
my jest.config.ts file :
// For a detailed explanation regarding each configuration property and type check, visit:
// https://jestjs.io/docs/configuration
// eslint-disable-next-line import/no-extraneous-dependencies
import { pathsToModuleNameMapper } from "ts-jest/dist";
import { compilerOptions } from "./tsconfig.json";
export default {
// All imported modules in your tests should be mocked automatically
automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\ssoylu\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["<rootDir>/**/*.ts"],
// The directory where Jest should output its coverage files
coverageDirectory: "tests/coverage",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ["/tests/"],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["json", "text", "lcov", "clover"],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
errorOnDeprecated: true,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
maxWorkers: "10%",
// An array of directory names to be searched recursively up from the requiring module's location
moduleDirectories: ["src", "node_modules"],
// An array of file extensions your modules use
moduleFileExtensions: ["js", "mjs", "ts", "tsx", "json"],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "ts-jest",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
resetMocks: true,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
rootDir: "./tests",
// A list of paths to directories that Jest should use to search for files in
// roots: ["tests", "src"],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ["**/launcher.test.ts?(x)"],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+quot;
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在
jest.config.ts
中配置路径,以便开玩笑解决模块。You should configure your paths in
jest.config.ts
in order for Jest to resolve the module.沙哑!
假设#1 您没有
绒毛阶段
config?HuskY!
Assumption #1 You have no
lint-staged
config? ????Update: after thinking again, if this is an issue, then you have another issue, as this would only solve the problem for linting but you're saying it's the same for Jest. Anyway, there could be 2 problems ^^ disguised as 1.`
It's either
lintstagedrc.yml|yaml|json
...or example from
package.json
It's also explained by
lint-staged
:Assumption #2 different path alias notation
It's probably nothing, but you could also just set the paths like this:
I haven't tested it with:
*
notation as in your config@
prefix is also not used in our project