我正在把我的TypeScript项目切换到(pnpm)monorepo,并且在让测试正常运行时遇到了麻烦。我有一个jest.config.js,它使用了一个同样用TypeScript编写的自定义testEnvironment
。然而,自从我把这个特定的项目移到我的packages目录中进行monorepo重构之后,jest抛出了一个错误并且没有运行任何测试:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\workspaces\repos\the-monorepo\packages\testproject\source\testtools\jsdom-environment-global.spec.ts
我用@swc/jest和ts-jest试了一下,看了看How to use TypeScript in a Custom Test Environment file in Jest?(这让我想“为什么它会工作?”),不管什么原因,昨天它工作得很好。我清理了jest缓存并重新安装了所有node_modules,但没有用。我还在package.json中找到了与"type": "module"
相关的答案,但这不适用于我的包。它不是ESM。
下面是jest.config.js的外观:
/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
silent: true,
testEnvironment: "<rootDir>/source/testtools/jsdom-environment-global.spec.ts",
roots: [
"<rootDir>/source"
],
maxWorkers: "50%",
transform: {
"^.+\\.(t|j)s$": ["@swc/jest", {
sourceMaps: "inline",
module: {
strict: false,
strictMode: false
},
jsc: {
target: "es2021",
parser: {
syntax: "typescript",
dynamicImport: true
}
}
}]
},
transformIgnorePatterns: [
"node_modules"
],
testMatch: [
"**/*/*.spec.ts",
"**/*/*.test.ts",
"!**/playwright-tests/**",
"!**/playwright-tests-smoke/**"
],
moduleFileExtensions: ["ts", "js", "node", "json"],
reporters: [
"default"
],
globals: {
self: {},
navigator: {},
jasmine: {},
__UNIT__: true
},
coverageDirectory: "test-results",
collectCoverage: false,
collectCoverageFrom: [
"./source/**/*.ts"
],
coveragePathIgnorePatterns: [
"/\\.spec\\.ts$/i",
"/.*node_modules.*/",
"/.*testtools.*/"
],
coverageReporters: [
"lcov", "cobertura"
],
coverageProvider: "v8",
resetMocks: true,
restoreMocks: true,
resetModules: true,
setupFilesAfterEnv: [
"jest-extended/all",
"<rootDir>/source/testtools/setup.spec.ts"
],
testPathIgnorePatterns: [
"<rootDir>/source/testtools/",
"<rootDir>/source/smoke-tests/",
"<rootDir>/source/performance-tests/",
"<rooDir>/source/playwright-tests/",
"<rooDir>/source/playwright-tests-smoke/"
],
moduleNameMapper: {
"^@test-helpers": "<rootDir>/source/testtools/index.spec.ts",
"^@test-tools/(.*)": "<rootDir>/source/testtools/$1",
'^(\\.{1,2}/.*)\\.js$': '$1'
}
};
module.exports = config;
如果testEnvironment
是一个TypeScript文件,为什么jest不能解析它?
1条答案
按热度按时间jchrr9hc1#
我发现了问题:似乎有一些关于转换器没有被应用到ESM文件的混乱.在我的例子中,
jsdom-environment-global.spec.ts
从我的monorepo中的一个不同的包导入了一个ESM模块.这个导入触发了一个异常,因为jest试图通过require()
导入它,该异常被捕获,然后通过动态导入再次导入。此动态导入然后引发ts
是未知异常的异常。I'我不知道为什么这些文件还没有被转换,但从How to use TypeScript in a Custom Test Environment file in Jest?开始,这似乎是正常的。底线:不要在jest
testEnvironment
模块中从ESM文件导入。