• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kulshekhar / ts-jest / 4897835899

pending completion
4897835899

push

github

GitHub
build(deps): Update dependency @commitlint/config-angular to ^17.6.3 (#4123)

937 of 1054 branches covered (88.9%)

Branch coverage included in aggregate %.

4055 of 4154 relevant lines covered (97.62%)

518.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.81
/src/cli/config/init.ts
1
/**
3✔
2
 * This has been written quickly. While trying to improve I realised it'd be better to have it in Jest...
3✔
3
 * ...and I saw a merged PR with `jest --init` tool!
3✔
4
 * TODO: see what's the best path for this
3✔
5
 */
3✔
6

3✔
7
import { existsSync, readFileSync, writeFileSync } from 'fs'
3✔
8
import { basename, join } from 'path'
3✔
9

3✔
10
import { stringify as stringifyJson5 } from 'json5'
3✔
11

3✔
12
import type { CliCommand, CliCommandArgs } from '..'
3✔
13
import type { JestConfigWithTsJest, TsJestTransformerOptions } from '../../types'
3✔
14
import { type TsJestPresetDescriptor, defaults, jsWIthBabel, jsWithTs } from '../helpers/presets'
3✔
15

3✔
16
/**
3✔
17
 * @internal
3✔
18
 */
3✔
19
export const run: CliCommand = async (args: CliCommandArgs /* , logger: Logger */) => {
3✔
20
  const file = args._[0]?.toString() ?? 'jest.config.js'
12✔
21
  const filePath = join(process.cwd(), file)
12✔
22
  const name = basename(file)
12✔
23
  const isPackage = name === 'package.json'
12✔
24
  const exists = existsSync(filePath)
12✔
25
  const pkgFile = isPackage ? filePath : join(process.cwd(), 'package.json')
12✔
26
  const hasPackage = isPackage || existsSync(pkgFile)
12✔
27
  // read config
12✔
28
  const { jestPreset = true, tsconfig: askedTsconfig, force, jsdom } = args
12✔
29
  const tsconfig =
12✔
30
    askedTsconfig === 'tsconfig.json' ? undefined : (askedTsconfig as TsJestTransformerOptions['tsconfig'])
12!
31
  // read package
12✔
32
  const pkgJson = hasPackage ? JSON.parse(readFileSync(pkgFile, 'utf8')) : {}
12!
33

12✔
34
  // auto js/babel
12✔
35
  let { js: jsFilesProcessor, babel: shouldPostProcessWithBabel } = args
12✔
36
  // set defaults for missing options
12✔
37
  if (jsFilesProcessor == null) {
12✔
38
    // set default js files processor depending on whether the user wants to post-process with babel
6✔
39
    jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined
6!
40
  } else if (shouldPostProcessWithBabel == null) {
6!
41
    // auto enables babel post-processing if the user wants babel to process js files
×
42
    shouldPostProcessWithBabel = jsFilesProcessor === 'babel'
×
43
  }
×
44

12✔
45
  // preset
12✔
46
  let preset: TsJestPresetDescriptor | undefined
12✔
47
  if (jsFilesProcessor === 'babel') {
12!
48
    preset = jsWIthBabel
×
49
  } else if (jsFilesProcessor === 'ts') {
12✔
50
    preset = jsWithTs
6✔
51
  } else {
6✔
52
    preset = defaults
6✔
53
  }
6✔
54

12✔
55
  if (isPackage && !exists) {
12!
56
    throw new Error(`File ${file} does not exists.`)
×
57
  } else if (!isPackage && exists && !force) {
12!
58
    throw new Error(`Configuration file ${file} already exists.`)
×
59
  }
×
60
  if (!isPackage && !name.endsWith('.js')) {
12!
61
    throw new TypeError(`Configuration file ${file} must be a .js file or the package.json.`)
×
62
  }
×
63
  if (hasPackage && pkgJson.jest) {
12!
64
    if (force && !isPackage) {
×
65
      delete pkgJson.jest
×
66
      writeFileSync(pkgFile, JSON.stringify(pkgJson, undefined, '  '))
×
67
    } else if (!force) {
×
68
      throw new Error(`A Jest configuration is already set in ${pkgFile}.`)
×
69
    }
×
70
  }
×
71

12✔
72
  // build configuration
12✔
73
  let body: string
12✔
74

12✔
75
  if (isPackage) {
12✔
76
    // package.json config
6✔
77
    const jestConfig: JestConfigWithTsJest = jestPreset ? { preset: preset.name } : { ...preset.value }
6✔
78
    if (!jsdom) jestConfig.testEnvironment = 'node'
6✔
79
    const transformerConfig = Object.entries(jestConfig.transform ?? {}).reduce(
6✔
80
      (acc, [fileRegex, transformerConfig]) => {
6✔
81
        if (tsconfig || shouldPostProcessWithBabel) {
3!
82
          const tsJestConf: TsJestTransformerOptions = {}
3✔
83
          if (tsconfig) tsJestConf.tsconfig = tsconfig
3✔
84
          if (shouldPostProcessWithBabel) tsJestConf.babelConfig = true
3✔
85

3✔
86
          return {
3✔
87
            ...acc,
3✔
88
            [fileRegex]:
3✔
89
              typeof transformerConfig === 'string'
3✔
90
                ? [transformerConfig, tsJestConf]
3!
91
                : [transformerConfig[0], { ...transformerConfig[1], ...tsJestConf }],
3✔
92
          }
3✔
93
        }
3✔
94

×
95
        return {
×
96
          ...acc,
×
97
          [fileRegex]: transformerConfig,
×
98
        }
×
99
      },
6✔
100
      {},
6✔
101
    )
6✔
102
    if (Object.keys(transformerConfig).length) {
6✔
103
      jestConfig.transform = {
3✔
104
        ...jestConfig.transform,
3✔
105
        ...transformerConfig,
3✔
106
      }
3✔
107
    }
3✔
108
    body = JSON.stringify({ ...pkgJson, jest: jestConfig }, undefined, '  ')
6✔
109
  } else {
6✔
110
    // js config
6✔
111
    const content = []
6✔
112
    if (!jestPreset) {
6✔
113
      content.push(`${preset.jsImport('tsjPreset')};`, '')
3✔
114
    }
3✔
115
    content.push(`/** @type {import('ts-jest').JestConfigWithTsJest} */`)
6✔
116
    content.push('module.exports = {')
6✔
117
    if (jestPreset) {
6✔
118
      content.push(`  preset: '${preset.name}',`)
3✔
119
    } else {
3✔
120
      content.push('  ...tsjPreset,')
3✔
121
    }
3✔
122
    if (!jsdom) content.push("  testEnvironment: 'node',")
6✔
123

6✔
124
    if (tsconfig || shouldPostProcessWithBabel) {
6✔
125
      content.push('  transform: {')
3✔
126
      content.push("    '^.+\\\\.[tj]sx?$': ['ts-jest', {")
3✔
127
      if (tsconfig) content.push(`      tsconfig: ${stringifyJson5(tsconfig)},`)
3✔
128
      if (shouldPostProcessWithBabel) content.push('      babelConfig: true,')
3✔
129
      content.push('    }],')
3✔
130
      content.push('  },')
3✔
131
    }
3✔
132
    content.push('};')
6✔
133

6✔
134
    // join all together
6✔
135
    body = content.join('\n')
6✔
136
  }
6✔
137

12✔
138
  writeFileSync(filePath, body)
12✔
139

12✔
140
  process.stderr.write(`
12✔
141
Jest configuration written to "${filePath}".
12✔
142
`)
12✔
143
}
12✔
144

3✔
145
/**
3✔
146
 * @internal
3✔
147
 */
3✔
148
export const help: CliCommand = async () => {
3✔
149
  process.stdout.write(`
3✔
150
Usage:
3✔
151
  ts-jest config:init [options] [<config-file>]
3✔
152

3✔
153
Arguments:
3✔
154
  <config-file>         Can be a js or json Jest config file. If it is a
3✔
155
                        package.json file, the configuration will be read from
3✔
156
                        the "jest" property.
3✔
157
                        Default: jest.config.js
3✔
158

3✔
159
Options:
3✔
160
  --force               Discard any existing Jest config
3✔
161
  --js ts|babel         Process .js files with ts-jest if 'ts' or with
3✔
162
                        babel-jest if 'babel'
3✔
163
  --no-jest-preset      Disable the use of Jest presets
3✔
164
  --tsconfig <file>     Path to the tsconfig.json file
3✔
165
  --babel               Pipe babel-jest after ts-jest
3✔
166
  --jsdom               Use jsdom as test environment instead of node
3✔
167
`)
3✔
168
}
3✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc