【发布时间】: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