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

标签 typescript jestjs ts-jest

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

enter image description here

我想在 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 Code 中提示任何事情,但是当使用 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. global-setup 文件的开头添加 require('tsconfig-paths/register');

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

关于typescript - 未经 TS-Jest 处理的非测试 TypeScript 文件。在运行时找不到具有绝对路径的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67889450/

相关文章:

angular - 以 Angular 6 从 html 导出 Pdf

typescript - AWS CDK - 构造函数参数不匹配

angular - 如何让 jest 只对 src 文件夹 Angular 中的文件运行测试?

带有 Firestore 的 Angular Material MatTableDataSource

Angular 4拦截器不设置标题

javascript - 开 Jest 模拟 aws-sdk ReferenceError : Cannot access before initialization

angularjs - 使用 Jest 对 AngularJS 指令进行单元测试

javascript - 针对剧烈变异的远程 API 进行快照测试 API 客户端

typescript - Jest 模拟节点模块不适用于 typescript

javascript - 如何在 Global Jest 设置中查找别名?