Skip to content

Commit

Permalink
fix: add unit test and e2e test
Browse files Browse the repository at this point in the history
  • Loading branch information
longlho authored and ahnpnl committed Sep 18, 2020
1 parent 798beaa commit acb2303
Show file tree
Hide file tree
Showing 9 changed files with 178 additions and 17 deletions.
47 changes: 43 additions & 4 deletions docs/user/config/astTransformers.md
Expand Up @@ -14,6 +14,46 @@ The option is `astTransformers` and it allows ones to specify which 3 types of T

### Examples

#### Basic Transformers

<div class="row"><div class="col-md-6" markdown="block">

```js
// jest.config.js
module.exports = {
// [...]
globals: {
'ts-jest': {
astTransformers: {
before: ['my-custom-transformer'],
},
},
},
}
```

</div><div class="col-md-6" markdown="block">

```js
// OR package.json
{
// [...]
"jest": {
"globals": {
"ts-jest": {
astTransformers: {
"before": ["my-custom-transformer"]
}
}
}
}
}
```

</div></div>

#### Configuring transformers with options

<div class="row"><div class="col-md-6" markdown="block">

```js
Expand All @@ -24,10 +64,9 @@ module.exports = {
'ts-jest': {
astTransformers: {
before: [
'my-custom-transformer',
{
path: 'my-custom-transformer-that-needs-extra-opts',
options: {},
options: {}, // extra options to pass to transformers here
},
],
},
Expand All @@ -46,9 +85,9 @@ module.exports = {
"globals": {
"ts-jest": {
astTransformers: {
"before": ["my-custom-transformer", {
"before": [{
path: 'my-custom-transformer-that-needs-extra-opts',
options: {}
options: {} // extra options to pass to transformers here
}]
}
}
Expand Down
18 changes: 18 additions & 0 deletions e2e/__cases__/ast-transformers/with-extra-options/foo.js
@@ -0,0 +1,18 @@
const { LogContexts, LogLevels } = require('bs-logger')

function factory(cs, extraOpts = Object.create(null)) {
const logger = cs.logger.child({ namespace: 'dummy-transformer' })
const ts = cs.compilerModule
logger.debug('Dummy transformer with extra options', JSON.stringify(extraOpts))

function createVisitor(_ctx, _sf) {
return (node) => node
}

return (ctx) =>
logger.wrap({ [LogContexts.logLevel]: LogLevels.debug, call: null }, 'visitSourceFileNode(): dummy', (sf) =>
ts.visitNode(sf, createVisitor(ctx, sf))
)
}

exports.factory = factory
@@ -0,0 +1,5 @@
const a = 1;

it('should pass', () => {
expect(a).toEqual(1);
})
19 changes: 19 additions & 0 deletions e2e/__tests__/__snapshots__/ast-transformers.test.ts.snap
@@ -0,0 +1,19 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`AST transformers with extra options should pass using template "default" 1`] = `
Array [
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
]
`;

exports[`AST transformers with extra options should pass using template "with-babel-7" 1`] = `
Array [
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
]
`;

exports[`AST transformers with extra options should pass using template "with-babel-7-string-config" 1`] = `
Array [
"[level:20] Dummy transformer with extra options {\\"foo\\":\\"bar\\"}",
]
`;
38 changes: 38 additions & 0 deletions e2e/__tests__/ast-transformers.test.ts
@@ -0,0 +1,38 @@
import { configureTestCase } from '../__helpers__/test-case'
import { allValidPackageSets } from '../__helpers__/templates'
import { existsSync } from "fs"
import { LogContexts, LogLevels } from 'bs-logger'

describe('AST transformers', () => {
describe('with extra options', () => {
const testCase = configureTestCase('ast-transformers/with-extra-options', {
env: { TS_JEST_LOG: 'ts-jest.log' },
tsJestConfig: {
astTransformers: {
before: [{
path: require.resolve('../__cases__/ast-transformers/with-extra-options/foo'),
options: {
foo: 'bar',
},
}],
},
},
})

testCase.runWithTemplates(allValidPackageSets, 0, (runTest, { testLabel }) => {
it(testLabel, () => {
const result = runTest()
expect(result.status).toBe(0)
expect(existsSync(result.logFilePath)).toBe(true)
const filteredEntries = result.logFileEntries
// keep only debug and above
.filter(m => (m.context[LogContexts.logLevel] || 0) >= LogLevels.debug)
// simplify entries
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
.map(e => result.normalize(`[level:${e.context[LogContexts.logLevel]}] ${e.message}`))
.filter(logging => logging.includes('Dummy transformer with extra options'))
expect(filteredEntries).toMatchSnapshot()
})
})
})
})
2 changes: 1 addition & 1 deletion e2e/__tests__/path-mapping.test.ts
Expand Up @@ -13,7 +13,7 @@ function executeTest(rootDirs?: string[]) {
},
astTransformers: {
before: [
{path: 'ts-jest/dist/transformers/path-mapping'}
'ts-jest/dist/transformers/path-mapping'
],
},
},
Expand Down
11 changes: 11 additions & 0 deletions src/config/__snapshots__/config-set.spec.ts.snap
Expand Up @@ -355,3 +355,14 @@ exports[`tsJest transformers should display deprecation warning message when con
"[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
"
`;

exports[`tsJest transformers should support transformers with options 1`] = `
Array [
Object {
"options": Object {
"foo": 1,
},
"path": Any<String>,
},
]
`;
31 changes: 31 additions & 0 deletions src/config/config-set.spec.ts
Expand Up @@ -161,6 +161,37 @@ describe('tsJest', () => {
expect(logger.target.lines[1]).toMatchSnapshot()
})

it('should support transformers with options', () => {
const cs = createConfigSet({
jestConfig: {
rootDir: 'src',
cwd: 'src',
globals: {
'ts-jest': {
astTransformers: {
before: [
{
path: 'dummy-transformer',
options: {
foo: 1,
},
},
],
},
},
},
} as any,
logger,
resolve: null,
})

expect(cs.tsJest.transformers.before).toMatchSnapshot([
{
path: expect.any(String),
},
])
})

it.each([
{},
{
Expand Down
24 changes: 12 additions & 12 deletions src/config/config-set.ts
Expand Up @@ -57,7 +57,7 @@ import { TSError } from '../utils/ts-error'
const logger = rootLogger.child({ namespace: 'config' })

interface AstTransformerObj<T = Record<string, unknown>> {
module: AstTransformerDesc
transformModule: AstTransformerDesc
options?: T
}

Expand Down Expand Up @@ -432,7 +432,7 @@ export class ConfigSet {
let astTransformers: AstTransformer = {
before: [
...internalAstTransformers.map((transformer) => ({
module: transformer,
transformModule: transformer,
})),
],
}
Expand All @@ -444,10 +444,10 @@ export class ConfigSet {
...transformers.before.map((transformer) =>
typeof transformer === 'string'
? {
module: require(transformer),
transformModule: require(transformer),
}
: {
module: require(transformer.path),
transformModule: require(transformer.path),
options: transformer.options,
},
),
Expand All @@ -460,10 +460,10 @@ export class ConfigSet {
after: transformers.after.map((transformer) =>
typeof transformer === 'string'
? {
module: require(transformer),
transformModule: require(transformer),
}
: {
module: require(transformer.path),
transformModule: require(transformer.path),
options: transformer.options,
},
),
Expand All @@ -475,10 +475,10 @@ export class ConfigSet {
afterDeclarations: transformers.afterDeclarations.map((transformer) =>
typeof transformer === 'string'
? {
module: require(transformer),
transformModule: require(transformer),
}
: {
module: require(transformer.path),
transformModule: require(transformer.path),
options: transformer.options,
},
),
Expand All @@ -494,14 +494,14 @@ export class ConfigSet {
@Memoize()
get tsCustomTransformers(): CustomTransformers {
let customTransformers: CustomTransformers = {
before: this.astTransformers.before.map((t) => t.module.factory(this, t.options)) as TransformerFactory<
before: this.astTransformers.before.map((t) => t.transformModule.factory(this, t.options)) as TransformerFactory<
SourceFile
>[],
}
if (this.astTransformers.after) {
customTransformers = {
...customTransformers,
after: this.astTransformers.after.map((t) => t.module.factory(this, t.options)) as TransformerFactory<
after: this.astTransformers.after.map((t) => t.transformModule.factory(this, t.options)) as TransformerFactory<
SourceFile
>[],
}
Expand All @@ -510,7 +510,7 @@ export class ConfigSet {
customTransformers = {
...customTransformers,
afterDeclarations: this.astTransformers.afterDeclarations.map((t) =>
t.module.factory(this, t.options),
t.transformModule.factory(this, t.options),
) as TransformerFactory<Bundle | SourceFile>[],
}
}
Expand Down Expand Up @@ -721,7 +721,7 @@ export class ConfigSet {
digest: this.tsJestDigest,
transformers: Object.values(this.astTransformers)
.reduce((acc, val) => acc.concat(val), [])
.map((t: AstTransformerDesc) => `${t.name}@${t.version}`),
.map(({ transformModule }: AstTransformerObj) => `${transformModule.name}@${transformModule.version}`),
jest,
tsJest: this.tsJest,
babel: this.babel,
Expand Down

0 comments on commit acb2303

Please sign in to comment.