Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bump babel-jest and other jest dependencies to v29 #85

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ module.exports = {
}
]
},
testEnvironment: 'jest-environment-jsdom',
/// This will resolve any tsconfig.compilerOptions.paths
moduleNameMapper: hq.get('jest'),
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/types/' ],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
snapshotFormat: {
escapeString: true, // Note: disabling this value leads to failed snapshots!
},
}
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"devDependencies": {
"@babel/preset-typescript": "^7.13.0",
"@swc/core": "^1.2.50",
"@types/jest": "^26.0.21",
"@types/jest": "^29.2.5",
"@types/mock-fs": "^4.13.0",
"@types/node": "^14.14.35",
"@types/react": "^17.0.3",
Expand All @@ -40,8 +40,9 @@
"aria-build": "^0.7.3",
"aria-fs": "^0.7.3",
"esbuild": "^0.8.49",
"jest": "^26.6.3",
"jest-config": "^26.6.3",
"jest": "^29.3.1",
"jest-config": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"prettier": "^2.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
Expand All @@ -51,7 +52,7 @@
"dependencies": {
"@babel/core": "^7.13.10",
"@babel/plugin-transform-modules-commonjs": "^7.13.8",
"babel-jest": "^26.6.3"
"babel-jest": "^29.3.1"
},
"babel": {
"presets": [
Expand Down
82 changes: 34 additions & 48 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,45 @@
import { extname } from 'path'

import { Config } from '@jest/types'
import { TransformOptions as JestTransformOptions, Transformer } from '@jest/transform'
import { Format, Loader, TransformOptions, transformSync } from 'esbuild'
import type { SyncTransformer, TransformerCreator } from '@jest/transform'
import type { TransformOptions } from 'esbuild'
import { transformSync } from 'esbuild'

import { Options } from './options'
import { getExt, loaders } from './utils'

const createTransformer = (options?: Options) => ({
process(content: string,
filename: string,
config: Config.ProjectConfig,
opts?: JestTransformOptions
) {
const sources = { code: content }
const ext = getExt(filename), extName = extname(filename).slice(1)
import { parseLoader } from './utils'

const enableSourcemaps = options?.sourcemap || false
const loader = (options?.loaders && options?.loaders[ext]
? options.loaders[ext]
: loaders.includes(extName) ? extName: 'text'
) as Loader
const sourcemaps: Partial<TransformOptions> = enableSourcemaps
? { sourcemap: true, sourcesContent: false, sourcefile: filename }
: {}
const createTransformer: TransformerCreator<SyncTransformer<Options>, Options> = transformerConfig => ({
canInstrument: true,
process(sourceText, sourcePath, options) {
let sourceCode = sourceText

/// this logic or code from
/// https://github.com/threepointone/esjest-transform/blob/main/src/index.js
/// this will support the jest.mock
/// https://github.com/aelbore/esbuild-jest/issues/12
/// TODO: transform the jest.mock to a function using babel traverse/parse then hoist it
if (sources.code.indexOf("ock(") >= 0 || opts?.instrument) {
const source = require('./transformer').babelTransform({
sourceText: content,
sourcePath: filename,
config,
options: opts
})
sources.code = source
if (sourceCode.indexOf("ock(") >= 0 || options?.instrument) {
const { code } = require('./transformer').babelTransform(sourceText, sourcePath, options)
sourceCode = code
}

const result = transformSync(sources.code, {
loader,
format: options?.format as Format || 'cjs',
target: options?.target || 'es2018',
...(options?.jsxFactory ? { jsxFactory: options.jsxFactory }: {}),
...(options?.jsxFragment ? { jsxFragment: options.jsxFragment }: {}),
...sourcemaps
})

const buildConfig: TransformOptions = {
loader: parseLoader(sourcePath, transformerConfig.loaders),
format: transformerConfig?.format || 'cjs',
target: transformerConfig?.target || 'es2018',
}

const isSourcemaps = !!transformerConfig?.sourcemap;
if (isSourcemaps) {
buildConfig.sourcemap = true
buildConfig.sourcesContent = false
buildConfig.sourcefile = sourcePath
}

if (transformerConfig?.jsxFactory) buildConfig.jsxFactory = transformerConfig.jsxFactory
if (transformerConfig?.jsxFragment) buildConfig.jsxFragment = transformerConfig.jsxFragment

const result = transformSync(sourceCode, buildConfig)

let { map, code } = result;
if (enableSourcemaps) {
if (isSourcemaps) {
map = {
...JSON.parse(result.map),
sourcesContent: null,
Expand All @@ -65,13 +54,10 @@ const createTransformer = (options?: Options) => ({

return { code, map }
}
})

const transformer: Pick<Transformer, 'canInstrument' | 'createTransformer'> = {
canInstrument: true,
createTransformer
}
});

export * from './options'

export default transformer
export default {
createTransformer
}
8 changes: 3 additions & 5 deletions src/options.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Loader } from 'esbuild'
import { Format, Loader } from 'esbuild'

export interface Options {
jsxFactory?: string
jsxFragment?: string
sourcemap?: boolean | 'inline' | 'external'
loaders?: {
[ext: string]: Loader
},
loaders?: Record<string, Loader>
target?: string
format?: string
format?: Format
}
20 changes: 2 additions & 18 deletions src/transformer.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,8 @@
import { TransformOptions } from '@jest/transform'
import { Config } from '@jest/types'

import babelJest from 'babel-jest'

const { process } = babelJest.createTransformer({
export const { process: babelTransform } = babelJest.createTransformer({
plugins: [ "@babel/plugin-transform-modules-commonjs" ],
parserOpts: {
plugins: ["jsx", "typescript"],
}
})

export interface BabelTransformOptions {
sourceText: string
sourcePath: string
config: Config.ProjectConfig
options?: TransformOptions
}

export function babelTransform(opts: BabelTransformOptions) {
const { sourceText, sourcePath, config, options } = opts
const babelResult = process(sourceText, sourcePath, config, options) as { code: string }
return babelResult.code
}
});
19 changes: 15 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Loader } from 'esbuild'
import type { Options } from './options'
import path from 'path'

export const loaders = ["js", "jsx", "ts", "tsx", "json"]

export const getExt = (str: string) => {
const getExt = (str: string) => {
const basename = path.basename(str);
const firstDot = basename.indexOf('.');
const lastDot = basename.lastIndexOf('.');
Expand All @@ -11,4 +11,15 @@ export const getExt = (str: string) => {
if (firstDot === lastDot) return extname

return basename.slice(firstDot, lastDot) + extname
}
}

const loaders = ["js", "jsx", "ts", "tsx", "json"]
const checkLoader = (extName: string = ''): extName is Loader => loaders.includes(extName)

export const parseLoader = (sourcePath: string, loaders: Options['loaders'] = {}): Loader => {
const ext = getExt(sourcePath)
const loader = loaders[ext]
if (loader) return loader
const extName = path.extname(sourcePath).slice(1)
return checkLoader(extName) ? extName : 'text'
}
31 changes: 27 additions & 4 deletions tests/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Config } from '@jest/types'

import fs from 'fs'
import path from 'path'

Expand All @@ -9,18 +11,39 @@ import { display } from '../examples/names-ts/index'
/// using @babel/preset-typescript
/// i was able to us directly the typescript code without bundle the code
import transformer, { Options } from '../src/index'
import { TransformOptions } from '@jest/transform'

// More info: https://github.com/facebook/jest/blob/61a64b53fe72b00fb17d7aabe5a54c4d415a845f/packages/test-utils/src/config.ts#L69
const config: Config.ProjectConfig = {
...defaults,
cwd: path.resolve(),
id: 'test_name',
moduleNameMapper: [],
rootDir: '/test_root_dir/',
sandboxInjectedGlobals: [],
snapshotResolver: undefined,
transform: [],
};

// More info: https://github.com/facebook/jest/blob/61a64b53fe72b00fb17d7aabe5a54c4d415a845f/packages/babel-jest/src/__tests__/index.ts#L54
const opts = {
cacheFS: new Map<string, string>(),
config,
configString: JSON.stringify(config),
instrument: false,
transformerConfig: {},
} as TransformOptions<Options>;

const process = (sourcePath: string, options?: Options) => {
const process = (sourcePath: string, options: Options = {}) => {
const content = fs.readFileSync(sourcePath, 'utf-8')

const Transformer = transformer.createTransformer({
format: 'esm',
sourcemap: true,
...(options || {})
...options
})

const config = { ...defaults, cwd: path.resolve() } as any
const output = Transformer.process(content, sourcePath, config) as { code: string, map: string }
const output = Transformer.process(content, sourcePath, opts) as { code: string, map: string }

return { ...output }
}
Expand Down
Loading