未经 TS-Jest 处理的非测试 TypeScript 文件。在运行时找不到具有绝对路径的模块

Non-test TypeScript files not processed by TS-Jest. Cannot find module with absolute path during runtime

我有一个使用 Playwright + TS-Jest 设置 E2E 测试的项目。为了组织我的测试,我使用页面对象模型。结构看起来像这样:

我想在 tsconfig.json 中使用 TypeScript paths 选项来清理测试文件和 POM 类 中的导入。经过反复试验,我想出了以下配置文件:

// tsconfig.json
{
    "compilerOptions": {
        "target": "es6",
        "lib": ["dom", "dom.iterable", "esnext"],
        "strict": true,
        "module": "commonjs",
        "noEmit": true,
        "types": ["@types/jest", "jest-playwright-preset"],
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "baseUrl": "src",
        "paths": {
            "models": ["models"],
            "models/*": ["models/*"],
            "config": ["../config"]
        }
    },
    "include": ["./src/**/*.ts"]
}

// jest.config.ts
import type { Config } from '@jest/types';
import playwrightPreset from 'jest-playwright-preset/jest-preset.json';

import { pathsToModuleNameMapper } from 'ts-jest/utils';
import { compilerOptions } from './tsconfig.json';

const config: Config.InitialOptions = {
    ...playwrightPreset,
    testRunner: 'jasmine2',
    setupFilesAfterEnv: [
        ...playwrightPreset.setupFilesAfterEnv,
    ],
    testMatch: ['**/__tests__/**/*.+(ts|js)', '**/?(*.)+(spec|test).+(ts|js)'],
    transform: {
        '^.+\.(ts)$': 'ts-jest',
    },
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
        prefix: '<rootDir>/src',
    }),
};

导入喜欢

// src/tests/home.test.ts
import { baseUrl, username, password } from 'config';
import { LoginPage, CookiesModal, NavbarComponent, SurveyEditPage } from 'models';

在测试文件中工作正常,不会造成任何问题。当我尝试在任何其他文件中使用它们时出现问题,例如

// src/global-setup.ts
import type { Config as JestConfig } from '@jest/types';
import { chromium, Page } from 'playwright';
import { username, password } from 'config';
import { CookiesModal, LoginPage } from './models';

尽管 TypeScript 在 Visual Studio 代码中没有任何问题,但是当 运行 使用 yarn test 进行测试时,我得到了一个错误

Error: Cannot find module 'config'

我认为其他 TS 文件似乎没有被 TS-Jest 或其他任何东西处理过。不过我可能完全错了。高度赞赏任何解决方案

我已经找到了这个 GitHub 问题的解决方案: https://github.com/kulshekhar/ts-jest/issues/1107#issuecomment-559759395

简而言之,默认情况下 ts-jest 转换的调用晚于应有的时间,因此没有机会处理所有文件。 tsconfig-paths 可以提供帮助:

  1. 使用 yarn add --dev tsconfig-paths
  2. 安装以上软件包
  3. global-setup 文件中,在文件的最开头添加 require('tsconfig-paths/register');

所有绝对导入都应该有效。