Skip to content

Commit

Permalink
feat(jest): use babel-jest by default for all code
Browse files Browse the repository at this point in the history
  • Loading branch information
Heymdall committed Apr 24, 2024
1 parent 86007bc commit 4ae24e3
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 53 deletions.
6 changes: 6 additions & 0 deletions .changeset/healthy-apricots-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'arui-scripts': major
---

Теперь по умолчанию jest будет использовать babel для преобразования ts-кода. Если по какой-то причине это
вас не устраивает - вы можете использовать настройку `jestUseTsJest`.
3 changes: 3 additions & 0 deletions packages/arui-scripts/docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,6 @@ const settings = {
Вместо этого будет запускаться отдельный процесс `tsc`, который будет выдавать сообщения об ошибках в типах только в консоль.

По умолчанию `true`.

#### jestUseTsJest
Позволяет использовать `ts-jest` вместо `babel-jest` для обработки `ts` файлов при запуске тестов. По умолчанию `false`.
24 changes: 5 additions & 19 deletions packages/arui-scripts/jest-preset.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,5 @@
module.exports = {
testRegex: 'src/.*(test|spec|/__test__/|/__tests__/).*\\.(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}'
],
testURL: 'http://localhost',
transform: {
'^.+\\.jsx?$': require.resolve('./build/configs/jest/babel-transform'),
'^.+\\.tsx?$': require.resolve('ts-jest'),
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': require.resolve('./build/configs/jest/file-transform')
},
moduleNameMapper: {
'\\.css$': require.resolve('./build/configs/jest/css-mock')
},
snapshotSerializers: [
require.resolve('jest-snapshot-serializer-class-name-to-string')
]
}
/* eslint-disable @typescript-eslint/no-var-requires */

const settings = require('./build/configs/jest/settings').default;

module.exports = settings;
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ describe('update-with-env', () => {
beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
jest.resetAllMocks();
})

afterAll(() => {
process.env = OLD_ENV;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('validate-settings-keys', () => {
name: 'ivan',
};

jest.spyOn(console, 'warn');
jest.spyOn(console, 'warn').mockImplementationOnce(() => {});

validateSettingsKeys(baseSettings, objectWithSettings);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export function getDefaultAppConfig(): AppConfigs {
webpack4Compatibility: false,
installServerSourceMaps: false,
disableDevWebpackTypecheck: true,
jestUseTsJest: false,

// image processing
dataUrlMaxSize: 1536,
Expand Down
1 change: 1 addition & 0 deletions packages/arui-scripts/src/configs/app-configs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export type AppConfigs = {
webpack4Compatibility: boolean;
installServerSourceMaps: boolean;
disableDevWebpackTypecheck: boolean;
jestUseTsJest: boolean;

// image processing
dataUrlMaxSize?: number;
Expand Down
35 changes: 2 additions & 33 deletions packages/arui-scripts/src/configs/jest/index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,10 @@
// TODO: remove eslint-disable
/* eslint-disable global-require */
/* eslint-disable @typescript-eslint/no-var-requires */
const fs = require('fs');
const { pathsToModuleNameMapper } = require('ts-jest');
const { parseConfigFileTextToJson } = require('typescript');
const merge = require('lodash.merge');
const configs = require('../app-configs').default;
const aruiJestPresets = require('./settings');

const tsConfigPath = configs.tsconfig;
const tsConfigText = fs.readFileSync(configs.tsconfig, 'utf8');
const tsConfig = parseConfigFileTextToJson(tsConfigPath, tsConfigText);
const tsConfigPaths = tsConfig.config.compilerOptions.paths || {};

const defaultJestConfig = {
testRegex: '(^.*src).*(((/__test__/|/__tests__/).*)|(test|spec|tests)).(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
// transform project js and ts files using babel ant ts transformers
transform: {
'^.+\\.jsx?$': require.resolve('./babel-transform'),
'^.+\\.tsx?$': require.resolve('ts-jest'),
// transform other files to simple empty strings
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': require.resolve('./file-transform'),
},
moduleNameMapper: {
// replace all css files with simple empty exports
'\\.css$': require.resolve('./css-mock'),
...pathsToModuleNameMapper(tsConfigPaths, { prefix: '<rootDir>/' }),
},
snapshotSerializers: [require.resolve('jest-snapshot-serializer-class-name-to-string')],
globals: {
'ts-jest': {
tsconfig: configs.tsconfig,
babelConfig: require('../babel-client').default,
},
},
};
const defaultJestConfig = aruiJestPresets;

let appJestConfig = {};

Expand Down
48 changes: 48 additions & 0 deletions packages/arui-scripts/src/configs/jest/settings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* eslint-disable @typescript-eslint/no-var-requires */
// Мы используем эти настройки сразу в двух местах - в jest-presets и в настройках jest-а, которые мы загружаем в самих скриптах
// jest-presets могут использоваться внешними утилитами, которые используют разработчики, настройки в скриптах
// используются при запуске `arui-scripts test`. Посколько в jest жестко зафиксировано где именно должен лежать файл с пресетами
// нам приходится отвязывать его от основного кода скриптов
const fs = require('fs');
const { pathsToModuleNameMapper } = require('ts-jest');
const { parseConfigFileTextToJson } = require('typescript');

const configs = require('../app-configs').default;

let tsConfigPaths = {};

if (configs.tsconfig) {
const tsConfigText = fs.readFileSync(configs.tsconfig, 'utf8');
const tsConfig = parseConfigFileTextToJson(configs.tsconfig, tsConfigText);

tsConfigPaths = tsConfig.config.compilerOptions.paths || {};
}

module.exports = {
testRegex: 'src/.*(((/__test__/|/__tests__/).*)|(test|spec|tests)).(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
testEnvironmentOptions: {
url: 'http://localhost',
},
transform: {
'^.+\\.jsx?$': require.resolve('./babel-transform'),
'^.+\\.tsx?$': configs.jestUseTsJest
? require.resolve('ts-jest')
: require.resolve('./babel-transform'),
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': require.resolve('./file-transform')
},
moduleNameMapper: {
// replace all css files with simple empty exports
'\\.css$': require.resolve('./css-mock'),
...pathsToModuleNameMapper(tsConfigPaths, { prefix: '<rootDir>/' }),
},
snapshotSerializers: [
require.resolve('jest-snapshot-serializer-class-name-to-string')
],
globals: {
'ts-jest': {
tsconfig: configs.tsconfig,
},
},
};

0 comments on commit 4ae24e3

Please sign in to comment.