【问题标题】:Non-test TypeScript files not processed by TS-Jest. Cannot find module with absolute path during runtimeTS-Jest 未处理的非测试 TypeScript 文件。在运行时找不到具有绝对路径的模块
【发布时间】:2021-08-25 14:10:03
【问题描述】:

我有一个使用 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 Code 中的任何内容,但在使用 yarn test 运行测试时出现错误

Error: Cannot find module 'config'

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

【问题讨论】:

  • 能帮忙提供github仓库吗?

标签: typescript jestjs ts-jest


【解决方案1】:

我已设法在此 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');

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

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2018-10-14
    • 2022-07-15
    • 2022-11-07
    • 1970-01-01
    • 2022-06-12
    • 2021-09-08
    • 2018-11-24
    相关资源
    最近更新 更多