I have a project with E2E tests setup with Playwright + TS-Jest. To organize my tests I use Page Object Model. Structure looks like that:
I wanted to use TypeScript paths
option in tsconfig.json
to clean up the imports both in test files as well as in POM classes. After some trial and error I came up with the following config files:
// 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',
}),
};
The imports like
// src/tests/home.test.ts
import { baseUrl, username, password } from 'config';
import { LoginPage, CookiesModal, NavbarComponent, SurveyEditPage } from 'models';
work correctly in test files and don't cause any trouble. Problems appear when I try to use them in any of the other files, ex.
// 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';
Although TypeScript doesn't complain about anything in Visual Studio Code, when running the tests with yarn test
I got an error
Error: Cannot find module 'config'
I think it looks like the other TS files are not processed by TS-Jest or anything else. I might be completely wrong though. Any solutions highly appreciated
I've managed to find solution in this GitHub issue: https://github.com/kulshekhar/ts-jest/issues/1107#issuecomment-559759395
In short, by default ts-jest
transform is invoked later than it should, so doesn't have a chance to process all the files. The tsconfig-paths
can help with that:
yarn add --dev tsconfig-paths
global-setup
file add require('tsconfig-paths/register');
at the very beginning of the file.All the absolute imports should work.