Skip to content

Commit fb5cd12

Browse files
committedJul 27, 2018
chore: simplify jest config test helper + moves test utils
- removes complex jest-config test helpers and simplify the tool - removes unused (anymore) rootDir() related code - improves readability of html-transform test - moves `test-utils.ts` into `__helpers__` dir
1 parent ddc8c32 commit fb5cd12

11 files changed

+116
-278
lines changed
 

‎scripts/tests.js

+11-6
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,19 @@ function getDirectories(rootDir) {
1313
});
1414
}
1515

16+
function isJestFolder(basename) {
17+
return basename.startsWith('__') && basename.endsWith('__');
18+
}
19+
20+
// TODO: later we could add a `.test-case-keep` empty file in each folder?
21+
// ...or move all into a `test-cases` dedicated directory
22+
function isTestCaseFolder(basename) {
23+
return !isJestFolder(basename);
24+
}
25+
1626
function createIntegrationMock() {
1727
const testsRoot = 'tests';
18-
const testCaseFolders = getDirectories(testsRoot).filter(function(testDir) {
19-
return !/^(?:utils|__.+__)$/.test(testDir);
20-
});
28+
const testCaseFolders = getDirectories(testsRoot).filter(isTestCaseFolder);
2129

2230
testCaseFolders.forEach(directory => {
2331
const testCaseNodeModules = path.join(testsRoot, directory, 'node_modules');
@@ -41,9 +49,6 @@ function createIntegrationMock() {
4149

4250
createIntegrationMock();
4351

44-
// HACK: allow us to change the `startDir()` during tests
45-
process.env.__RUNNING_TS_JEST_TESTS = Date.now();
46-
4752
const argv = process.argv.slice(2);
4853
argv.push('--no-cache');
4954
argv.push('--testPathPattern', '^(?!(.*watch.spec.ts$)).*');

‎src/preprocess.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@ export default function preprocess(
2222
const isHtmlFile = /\.html$/.test(filePath);
2323

2424
// This is to support angular 2. See https://github.com/kulshekhar/ts-jest/pull/145
25-
if (isHtmlFile && (jestConfig.globals as any).__TRANSFORM_HTML__) {
25+
if (
26+
isHtmlFile &&
27+
jestConfig.globals &&
28+
(jestConfig.globals as any).__TRANSFORM_HTML__
29+
) {
2630
src = 'module.exports=' + JSON.stringify(src) + ';';
2731
}
2832

‎src/utils/get-ts-config.ts

-13
Original file line numberDiff line numberDiff line change
@@ -95,19 +95,6 @@ function readCompilerOptions(configPath: string): CompilerOptions {
9595
return options;
9696
}
9797

98-
// function getStartDir(jestConfig: jest.ProjectConfig): string {
99-
// // This is needed because of the way our tests are structured.
100-
// // If this is being executed as a library (under node_modules)
101-
// // we want to start with the project directory that's three
102-
// // levels above.
103-
// // If this is being executed from the test suite, we want to start
104-
// // in the directory of the test
105-
106-
// // TODO: shouldn't we use the path of jest config here instead of '.' ?
107-
// // return process.env.__RUNNING_TS_JEST_TESTS ? process.cwd() : '.';
108-
// return process.env.__RUNNING_TS_JEST_TESTS ? process.cwd() : (jestConfig.rootDir || process.cwd());
109-
// }
110-
11198
// we don't need any data, just its full path
11299
const tsConfigReader = { basename: TSCONFIG_FILENAME, read: () => 0 };
113100

‎tests/__helpers__/jest-config.ts

-210
This file was deleted.

‎tests/__helpers__/mock-jest-config.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { TsJestConfig } from '../../dist/types';
2+
3+
const { resolve } = require.requireActual('path');
4+
5+
/**
6+
* Mock a jest config object for the test case in given folder
7+
*
8+
* Basically it defines `rootDir` and `cwd` properties to the full path of that
9+
* test case, as Jest would do.
10+
*
11+
* Accepts an optional config object, which will be defined on `globals.ts-jest`
12+
*/
13+
export default function mockJestConfig(
14+
testCaseFolder: string,
15+
tsJest: TsJestConfig | null = null,
16+
): jest.ProjectConfig {
17+
// resolves the path since jest would give a resolved path
18+
const rootDir = resolve(__dirname, '..', testCaseFolder);
19+
// create base jest config object
20+
let options: any = { rootDir, cwd: rootDir };
21+
// adds TS Jest options if any given
22+
if (tsJest != null) {
23+
options.globals = { 'ts-jest': tsJest };
24+
}
25+
return options;
26+
}

‎tests/__tests__/get-cache-key.spec.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import getCacheKey from '../../dist/utils/get-cache-key';
2-
import cfg from '../__helpers__/jest-config';
2+
import mockJestConfig from '../__helpers__/mock-jest-config';
33
import _getTSConfig from '../../dist/utils/get-ts-config';
44

55
jest.mock('../../dist/utils/get-ts-config', () => {
@@ -13,10 +13,11 @@ const getTSConfig: jest.Mock = _getTSConfig as any;
1313

1414
describe('getCacheKey', () => {
1515
const src = 'console.log(123);';
16-
const jestConfig = cfg.simple(null, {
16+
const jestConfig = {
17+
...mockJestConfig('simple'),
1718
transform: { '^.+\\\\.tsx?$': '../../preprocessor.js' },
1819
testRegex: '(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.(jsx?|tsx?)$',
19-
});
20+
};
2021
const filepath = `${jestConfig.rootDir}/some-file.ts`;
2122
const configStr = JSON.stringify(jestConfig);
2223
const options = { instrument: false, rootDir: jestConfig.rootDir };
+33-18
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,47 @@
11
import * as tsJest from '../../dist';
2-
import jestConfig from '../__helpers__/jest-config';
2+
import mockJestConfig from '../__helpers__/mock-jest-config';
33

4-
const config = jestConfig.simple({});
5-
const filePath = `${config.rootDir}/some-file.html`;
4+
const TEST_CASE = 'simple';
5+
const FILENAME = 'some-file.html';
66

7-
// wrap a transformed source so that we can fake a `require()` on it by calling the returned wrapper
8-
const wrap = (src: string) =>
9-
new Function(`var module={}; ${src} return module.exports;`) as any;
10-
11-
const source = `<div class="html-test">
7+
const fileContent = `<div class="html-test">
128
<span class="html-test__element">This is element</span>
139
<code>This is a backtilt \`</code>
1410
</div>`;
1511

1612
describe('Html transforms', () => {
1713
it('transforms html if config.globals.__TRANSFORM_HTML__ is set', () => {
14+
let jestConfig;
15+
1816
// get the untransformed version
19-
const untransformed = tsJest.process(source, filePath, { ...config });
20-
// ... then the one which should be transformed
21-
(config.globals as any).__TRANSFORM_HTML__ = true;
22-
const transformed = tsJest.process(source, filePath, config) as string;
23-
// ... finally the result of a `require('module-with-transformed-version')`
24-
const exported = wrap(transformed)();
17+
jestConfig = mockJestConfig(TEST_CASE);
18+
const untransformed = tsJest.process(
19+
fileContent,
20+
`${jestConfig.rootDir}/${FILENAME}`,
21+
jestConfig,
22+
);
23+
expect(untransformed).toBe(fileContent);
24+
expect(untransformed).toMatchSnapshot('untransformed');
2525

26-
expect(exported).toMatchSnapshot('module');
26+
// ... then the one which should be transformed
27+
jestConfig = {
28+
...mockJestConfig(TEST_CASE),
29+
globals: { __TRANSFORM_HTML__: true },
30+
};
31+
const transformed = tsJest.process(
32+
fileContent,
33+
`${jestConfig.rootDir}/${FILENAME}`,
34+
jestConfig,
35+
) as string;
36+
expect(transformed).not.toBe(fileContent);
2737
expect(transformed).toMatchSnapshot('source');
28-
expect(untransformed).toMatchSnapshot('untransformed');
29-
// requiring the transformed version should return the same string as the untransformed version
30-
expect(exported).toBe(untransformed);
38+
39+
// ... finally the result of a `require('module-with-transformed-version')`
40+
const value = eval(
41+
`(function(){const module={}; ${transformed}; return module.exports;})()`,
42+
);
43+
expect(value).toMatchSnapshot('module');
44+
// the value should be the same string as the source version
45+
expect(value).toBe(fileContent);
3146
});
3247
});

‎tests/__tests__/postprocess.spec.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ jest.mock('@babel/core', () => {
77
});
88

99
import { getPostProcessHook } from '../../dist/postprocess';
10-
import jestConfig from '../__helpers__/jest-config';
10+
import mockJestConfig from '../__helpers__/mock-jest-config';
1111

1212
describe('postprocess', () => {
1313
function runHook(jestConfig = {} as any) {
@@ -32,7 +32,7 @@ describe('postprocess', () => {
3232
const transformMock = require.requireMock('@babel/core').transform;
3333

3434
runHook();
35-
getPostProcessHook(jestConfig.simple())(
35+
getPostProcessHook(mockJestConfig('simple'))(
3636
{ code: 'input_code', map: '"input_source_map"' },
3737
'fake_file',
3838
{} as any,

‎tests/__tests__/tsconfig-comments.spec.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ jest.mock('path');
33
import * as fs from 'fs';
44
import getTSConfig from '../../dist/utils/get-ts-config';
55
import * as path from 'path';
6-
import cfg from '../__helpers__/jest-config';
6+
import mockJestConfig from '../__helpers__/mock-jest-config';
7+
8+
const TEST_CASE = 'tsconfig-test';
79

810
describe('parse tsconfig with comments', () => {
911
const configFile1 = './tests/tsconfig-test/allows-comments.json';
@@ -38,16 +40,16 @@ describe('parse tsconfig with comments', () => {
3840
// while allows-comments2.json does.
3941
// allow-comments.json extends allow-comments2.json
4042
it('should correctly read allow-comments.json', () => {
41-
const config = getTSConfig(
42-
cfg.tsconfigTest({ tsConfigFile: 'allows-comments.json' }),
43+
const tsConfig = getTSConfig(
44+
mockJestConfig(TEST_CASE, { tsConfigFile: 'allows-comments.json' }),
4345
);
44-
expect(config).toMatchSnapshot();
46+
expect(tsConfig).toMatchSnapshot();
4547
});
4648
it('should correctly read allow-comments2.json', () => {
47-
const config = getTSConfig(
48-
cfg.tsconfigTest({ tsConfigFile: 'allows-comments2.json' }),
49+
const tsConfig = getTSConfig(
50+
mockJestConfig(TEST_CASE, { tsConfigFile: 'allows-comments2.json' }),
4951
);
50-
expect(config).toMatchSnapshot();
52+
expect(tsConfig).toMatchSnapshot();
5153
});
5254
});
5355
});

‎tests/__tests__/tsconfig-default.spec.ts

+20-14
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ jest.mock('path');
44
import * as ts from 'typescript';
55
import getTSConfig from '../../dist/utils/get-ts-config';
66
import * as path from 'path';
7-
import jestConfig from '../__helpers__/jest-config';
7+
import mockJestConfig from '../__helpers__/mock-jest-config';
88
import getTSJestConfig from '../../dist/utils/get-ts-jest-config';
99

10+
const TEST_CASE = 'tsconfig-test';
11+
1012
describe('get default ts config', () => {
1113
beforeEach(() => {
1214
// Set up some mocked out file info before each test
@@ -19,44 +21,46 @@ describe('get default ts config', () => {
1921
// there is no tsconfig file in that test module
2022
((path as any) as MockedPath).__setBaseDir('./tests/jestconfig-test');
2123

22-
expect(() => getTSConfig(jestConfig.jestconfigTest(null))).toThrowError(
24+
expect(() => getTSConfig(mockJestConfig('jestconfig-test'))).toThrowError(
2325
/unable to find ts configuration file/i,
2426
);
2527
});
2628

2729
it('should correctly read tsconfig.json', () => {
28-
const result = getTSConfig(jestConfig.tsconfigTest(null));
30+
const result = getTSConfig(mockJestConfig(TEST_CASE));
2931

3032
expect(result).toMatchSnapshot();
3133
});
3234

3335
describe('new behavior (tsConfigFile & tsConfig)', () => {
3436
it('should be same results for null/undefined/etc.', () => {
35-
const result = getTSConfig(jestConfig.tsconfigTest(null));
36-
const resultEmptyParam = getTSConfig(jestConfig.tsconfigTest({}));
37+
const resultWithoutTsJestSection = getTSConfig(
38+
mockJestConfig(TEST_CASE, null),
39+
);
40+
const resultEmptyParam = getTSConfig(mockJestConfig(TEST_CASE, {}));
3741
const resultUndefinedContentFile = getTSConfig(
38-
jestConfig.tsconfigTest({ tsConfigFile: undefined }),
42+
mockJestConfig(TEST_CASE, { tsConfigFile: undefined }),
3943
);
4044
const resultNullContentFile = getTSConfig(
41-
jestConfig.tsconfigTest({ tsConfigFile: null }),
45+
mockJestConfig(TEST_CASE, { tsConfigFile: null }),
4246
);
4347

44-
expect(result).toEqual(resultEmptyParam);
45-
expect(result).toEqual(resultUndefinedContentFile);
46-
expect(result).toEqual(resultNullContentFile);
48+
expect(resultEmptyParam).toEqual(resultWithoutTsJestSection);
49+
expect(resultUndefinedContentFile).toEqual(resultWithoutTsJestSection);
50+
expect(resultNullContentFile).toEqual(resultWithoutTsJestSection);
4751
});
4852

4953
it('should be different results for different rootDir with same jest config.', () => {
50-
const rootConfig = getTSConfig(jestConfig.tsconfigTest());
54+
const rootConfig = getTSConfig(mockJestConfig(TEST_CASE));
5155
const subConfig = getTSConfig(
52-
jestConfig('tsconfig-test/tsconfig-module'),
56+
mockJestConfig(`${TEST_CASE}/tsconfig-module`),
5357
);
5458
expect(rootConfig).not.toEqual(subConfig);
5559
});
5660

5761
it('should not change the module if it is loaded from a non-default config file', () => {
5862
const config = getTSConfig(
59-
jestConfig.tsconfigTest({
63+
mockJestConfig(TEST_CASE, {
6064
tsConfigFile: 'tsconfig-module/custom-config.json',
6165
}),
6266
);
@@ -73,7 +77,9 @@ describe('get default ts config', () => {
7377
'./tests/tsconfig-test/tsconfig-module',
7478
);
7579

76-
const config = getTSConfig(jestConfig('tsconfig-test/tsconfig-module'));
80+
const config = getTSConfig(
81+
mockJestConfig(`${TEST_CASE}/tsconfig-module`),
82+
);
7783

7884
expect(config.module).toBe(ts.ModuleKind.CommonJS);
7985
});

‎tests/__tests__/tsconfig-string.spec.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ jest.mock('path');
33
import getTSConfig from '../../dist/utils/get-ts-config';
44
import * as ts from 'typescript';
55
import * as path from 'path';
6-
import cfg from '../__helpers__/jest-config';
6+
import mockJestConfig from '../__helpers__/mock-jest-config';
7+
8+
const TEST_CASE = 'tsconfig-test';
79

810
describe('get ts config from string', () => {
911
beforeEach(() => {
@@ -15,7 +17,7 @@ describe('get ts config from string', () => {
1517
describe('new behaviour (tsConfigFile & tsConfig)', () => {
1618
it('should correctly read my-tsconfig.json', () => {
1719
const result = getTSConfig(
18-
cfg.tsconfigTest({ tsConfigFile: 'my-tsconfig.json' }),
20+
mockJestConfig(TEST_CASE, { tsConfigFile: 'my-tsconfig.json' }),
1921
);
2022

2123
// snapshot would be enough here, but that adds a security in case we do not see it in a PR
@@ -25,7 +27,7 @@ describe('get ts config from string', () => {
2527

2628
it('should correctly resolve the "extends" directive', () => {
2729
const result = getTSConfig(
28-
cfg.tsconfigTest({ tsConfigFile: 'extends-tsconfig.json' }),
30+
mockJestConfig(TEST_CASE, { tsConfigFile: 'extends-tsconfig.json' }),
2931
);
3032

3133
// snapshot would be enough here, but that adds a security in case we do not see it in a PR
@@ -35,7 +37,7 @@ describe('get ts config from string', () => {
3537

3638
it('should correctly override any config in the "extends" directive', () => {
3739
const result = getTSConfig(
38-
cfg.tsconfigTest({
40+
mockJestConfig(TEST_CASE, {
3941
tsConfigFile: 'extends-with-overrides-tsconfig.json',
4042
}),
4143
);

0 commit comments

Comments
 (0)
Please sign in to comment.