Skip to content

Commit 1452ce4

Browse files
ahnpnllonglho
andauthored
feat(config): allow custom options in custom transformers (#1966)
Closes #1942 Co-authored-by: Long Ho <[email protected]>
1 parent 05d9b8b commit 1452ce4

File tree

9 files changed

+275
-37
lines changed

9 files changed

+275
-37
lines changed

docs/user/config/astTransformers.md

Lines changed: 58 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@ TypeScript AST transformers and provide them to `ts-jest` to include into compil
77

88
The option is `astTransformers` and it allows ones to specify which 3 types of TypeScript AST transformers to use with `ts-jest`:
99

10-
- `before` means your transformers get run before TS ones, which means your transformers will get raw TS syntax
11-
instead of transpiled syntax (e.g `import` instead of `require` or `define` ).
10+
- `before` means your transformers get run before TS ones, which means your transformers will get raw TS syntax
11+
instead of transpiled syntax (e.g `import` instead of `require` or `define` ).
1212
- `after` means your transformers get run after TS ones, which gets transpiled syntax.
1313
- `afterDeclarations` means your transformers get run during `d.ts` generation phase, allowing you to transform output type declarations.
1414

1515
### Examples
1616

17+
#### Basic Transformers
18+
1719
<div class="row"><div class="col-md-6" markdown="block">
1820

1921
```js
@@ -25,9 +27,52 @@ module.exports = {
2527
astTransformers: {
2628
before: ['my-custom-transformer'],
2729
},
30+
},
31+
},
32+
}
33+
```
34+
35+
</div><div class="col-md-6" markdown="block">
36+
37+
```js
38+
// OR package.json
39+
{
40+
// [...]
41+
"jest": {
42+
"globals": {
43+
"ts-jest": {
44+
astTransformers: {
45+
"before": ["my-custom-transformer"]
46+
}
47+
}
2848
}
2949
}
30-
};
50+
}
51+
```
52+
53+
</div></div>
54+
55+
#### Configuring transformers with options
56+
57+
<div class="row"><div class="col-md-6" markdown="block">
58+
59+
```js
60+
// jest.config.js
61+
module.exports = {
62+
// [...]
63+
globals: {
64+
'ts-jest': {
65+
astTransformers: {
66+
before: [
67+
{
68+
path: 'my-custom-transformer-that-needs-extra-opts',
69+
options: {}, // extra options to pass to transformers here
70+
},
71+
],
72+
},
73+
},
74+
},
75+
}
3176
```
3277

3378
</div><div class="col-md-6" markdown="block">
@@ -40,7 +85,10 @@ module.exports = {
4085
"globals": {
4186
"ts-jest": {
4287
astTransformers: {
43-
"before": ["my-custom-transformer"]
88+
"before": [{
89+
path: 'my-custom-transformer-that-needs-extra-opts',
90+
options: {} // extra options to pass to transformers here
91+
}]
4492
}
4593
}
4694
}
@@ -55,9 +103,9 @@ module.exports = {
55103
`ts-jest` is able to expose transformers for public usage to provide the possibility to opt-in/out for users. Currently
56104
the exposed transformers are:
57105

58-
- `path-mapping` convert alias import/export to relative import/export path base on `paths` in `tsconfig`.
59-
This transformer works similar to `moduleNameMapper` in `jest.config.js`. When using this transformer, one might not need
60-
`moduleNameMapper` anymore.
106+
- `path-mapping` convert alias import/export to relative import/export path base on `paths` in `tsconfig`.
107+
This transformer works similar to `moduleNameMapper` in `jest.config.js`. When using this transformer, one might not need
108+
`moduleNameMapper` anymore.
61109

62110
#### Example of opt-in transformers
63111

@@ -72,9 +120,9 @@ module.exports = {
72120
astTransformers: {
73121
before: ['ts-jest/dist/transformers/path-mapping'],
74122
},
75-
}
76-
}
77-
};
123+
},
124+
},
125+
}
78126
```
79127

80128
</div><div class="col-md-6" markdown="block">
@@ -97,7 +145,6 @@ module.exports = {
97145

98146
</div></div>
99147

100-
101148
### Writing custom TypeScript AST transformers
102149

103150
To write a custom TypeScript AST transformers, one can take a look at [the one](https://github.com/kulshekhar/ts-jest/tree/master/src/transformers) that `ts-jest` is using.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const { LogContexts, LogLevels } = require('bs-logger')
2+
3+
function factory(cs, extraOpts = Object.create(null)) {
4+
const logger = cs.logger.child({ namespace: 'dummy-transformer' })
5+
const ts = cs.compilerModule
6+
logger.debug('Dummy transformer with extra options', JSON.stringify(extraOpts))
7+
8+
function createVisitor(_ctx, _sf) {
9+
return (node) => node
10+
}
11+
12+
return (ctx) =>
13+
logger.wrap({ [LogContexts.logLevel]: LogLevels.debug, call: null }, 'visitSourceFileNode(): dummy', (sf) =>
14+
ts.visitNode(sf, createVisitor(ctx, sf))
15+
)
16+
}
17+
18+
exports.factory = factory
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const a = 1;
2+
3+
it('should pass', () => {
4+
expect(a).toEqual(1);
5+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`AST transformers with extra options should pass using template "default" 1`] = `
4+
Array [
5+
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
6+
]
7+
`;
8+
9+
exports[`AST transformers with extra options should pass using template "with-babel-7" 1`] = `
10+
Array [
11+
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
12+
]
13+
`;
14+
15+
exports[`AST transformers with extra options should pass using template "with-babel-7-string-config" 1`] = `
16+
Array [
17+
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
18+
]
19+
`;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { configureTestCase } from '../__helpers__/test-case'
2+
import { allValidPackageSets } from '../__helpers__/templates'
3+
import { existsSync } from "fs"
4+
import { LogContexts, LogLevels } from 'bs-logger'
5+
6+
describe('AST transformers', () => {
7+
describe('with extra options', () => {
8+
const testCase = configureTestCase('ast-transformers/with-extra-options', {
9+
env: { TS_JEST_LOG: 'ts-jest.log' },
10+
tsJestConfig: {
11+
astTransformers: {
12+
before: [{
13+
path: require.resolve('../__cases__/ast-transformers/with-extra-options/foo'),
14+
options: {
15+
foo: 'bar',
16+
},
17+
}],
18+
},
19+
},
20+
})
21+
22+
testCase.runWithTemplates(allValidPackageSets, 0, (runTest, { testLabel }) => {
23+
it(testLabel, () => {
24+
const result = runTest()
25+
expect(result.status).toBe(0)
26+
expect(existsSync(result.logFilePath)).toBe(true)
27+
const filteredEntries = result.logFileEntries
28+
// keep only debug and above
29+
.filter(m => (m.context[LogContexts.logLevel] || 0) >= LogLevels.debug)
30+
// simplify entries
31+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
32+
.map(e => result.normalize(`[level:${e.context[LogContexts.logLevel]}] ${e.message}`))
33+
.filter(logging => logging.includes('Dummy transformer with extra options'))
34+
expect(filteredEntries).toMatchSnapshot()
35+
})
36+
})
37+
})
38+
})

src/config/__snapshots__/config-set.spec.ts.snap

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,3 +355,14 @@ exports[`tsJest transformers should display deprecation warning message when con
355355
"[level:40] The configuration for astTransformers as string[] is deprecated and will be removed in ts-jest 27. Please define your custom AST transformers in a form of an object. More information you can check online documentation https://kulshekhar.github.io/ts-jest/user/config/astTransformers
356356
"
357357
`;
358+
359+
exports[`tsJest transformers should support transformers with options 1`] = `
360+
Array [
361+
Object {
362+
"options": Object {
363+
"foo": 1,
364+
},
365+
"path": Any<String>,
366+
},
367+
]
368+
`;

src/config/config-set.spec.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,37 @@ describe('tsJest', () => {
161161
expect(logger.target.lines[1]).toMatchSnapshot()
162162
})
163163

164+
it('should support transformers with options', () => {
165+
const cs = createConfigSet({
166+
jestConfig: {
167+
rootDir: 'src',
168+
cwd: 'src',
169+
globals: {
170+
'ts-jest': {
171+
astTransformers: {
172+
before: [
173+
{
174+
path: 'dummy-transformer',
175+
options: {
176+
foo: 1,
177+
},
178+
},
179+
],
180+
},
181+
},
182+
},
183+
} as any,
184+
logger,
185+
resolve: null,
186+
})
187+
188+
expect(cs.tsJest.transformers.before).toMatchSnapshot([
189+
{
190+
path: expect.any(String),
191+
},
192+
])
193+
})
194+
164195
it.each([
165196
{},
166197
{

0 commit comments

Comments
 (0)