gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:59:56 29 4
gpt4 key购买 nike

我有一个使用 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com