Skip to content

Commit

Permalink
chore: simplify jest config test helper + moves test utils
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
huafu committed Jul 27, 2018
1 parent ddc8c32 commit fb5cd12
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 278 deletions.
17 changes: 11 additions & 6 deletions scripts/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,19 @@ function getDirectories(rootDir) {
});
}

function isJestFolder(basename) {
return basename.startsWith('__') && basename.endsWith('__');
}

// TODO: later we could add a `.test-case-keep` empty file in each folder?
// ...or move all into a `test-cases` dedicated directory
function isTestCaseFolder(basename) {
return !isJestFolder(basename);
}

function createIntegrationMock() {
const testsRoot = 'tests';
const testCaseFolders = getDirectories(testsRoot).filter(function(testDir) {
return !/^(?:utils|__.+__)$/.test(testDir);
});
const testCaseFolders = getDirectories(testsRoot).filter(isTestCaseFolder);

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

createIntegrationMock();

// HACK: allow us to change the `startDir()` during tests
process.env.__RUNNING_TS_JEST_TESTS = Date.now();

const argv = process.argv.slice(2);
argv.push('--no-cache');
argv.push('--testPathPattern', '^(?!(.*watch.spec.ts$)).*');
Expand Down
6 changes: 5 additions & 1 deletion src/preprocess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export default function preprocess(
const isHtmlFile = /\.html$/.test(filePath);

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

Expand Down
13 changes: 0 additions & 13 deletions src/utils/get-ts-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,6 @@ function readCompilerOptions(configPath: string): CompilerOptions {
return options;
}

// function getStartDir(jestConfig: jest.ProjectConfig): string {
// // This is needed because of the way our tests are structured.
// // If this is being executed as a library (under node_modules)
// // we want to start with the project directory that's three
// // levels above.
// // If this is being executed from the test suite, we want to start
// // in the directory of the test

// // TODO: shouldn't we use the path of jest config here instead of '.' ?
// // return process.env.__RUNNING_TS_JEST_TESTS ? process.cwd() : '.';
// return process.env.__RUNNING_TS_JEST_TESTS ? process.cwd() : (jestConfig.rootDir || process.cwd());
// }

// we don't need any data, just its full path
const tsConfigReader = { basename: TSCONFIG_FILENAME, read: () => 0 };

Expand Down
210 changes: 0 additions & 210 deletions tests/__helpers__/jest-config.ts

This file was deleted.

26 changes: 26 additions & 0 deletions tests/__helpers__/mock-jest-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { TsJestConfig } from '../../dist/types';

const { resolve } = require.requireActual('path');

/**
* Mock a jest config object for the test case in given folder
*
* Basically it defines `rootDir` and `cwd` properties to the full path of that
* test case, as Jest would do.
*
* Accepts an optional config object, which will be defined on `globals.ts-jest`
*/
export default function mockJestConfig(
testCaseFolder: string,
tsJest: TsJestConfig | null = null,
): jest.ProjectConfig {
// resolves the path since jest would give a resolved path
const rootDir = resolve(__dirname, '..', testCaseFolder);
// create base jest config object
let options: any = { rootDir, cwd: rootDir };
// adds TS Jest options if any given
if (tsJest != null) {
options.globals = { 'ts-jest': tsJest };
}
return options;
}
7 changes: 4 additions & 3 deletions tests/__tests__/get-cache-key.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import getCacheKey from '../../dist/utils/get-cache-key';
import cfg from '../__helpers__/jest-config';
import mockJestConfig from '../__helpers__/mock-jest-config';
import _getTSConfig from '../../dist/utils/get-ts-config';

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

describe('getCacheKey', () => {
const src = 'console.log(123);';
const jestConfig = cfg.simple(null, {
const jestConfig = {
...mockJestConfig('simple'),
transform: { '^.+\\\\.tsx?$': '../../preprocessor.js' },
testRegex: '(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.(jsx?|tsx?)$',
});
};
const filepath = `${jestConfig.rootDir}/some-file.ts`;
const configStr = JSON.stringify(jestConfig);
const options = { instrument: false, rootDir: jestConfig.rootDir };
Expand Down
51 changes: 33 additions & 18 deletions tests/__tests__/html-transform.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,47 @@
import * as tsJest from '../../dist';
import jestConfig from '../__helpers__/jest-config';
import mockJestConfig from '../__helpers__/mock-jest-config';

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

// wrap a transformed source so that we can fake a `require()` on it by calling the returned wrapper
const wrap = (src: string) =>
new Function(`var module={}; ${src} return module.exports;`) as any;

const source = `<div class="html-test">
const fileContent = `<div class="html-test">
<span class="html-test__element">This is element</span>
<code>This is a backtilt \`</code>
</div>`;

describe('Html transforms', () => {
it('transforms html if config.globals.__TRANSFORM_HTML__ is set', () => {
let jestConfig;

// get the untransformed version
const untransformed = tsJest.process(source, filePath, { ...config });
// ... then the one which should be transformed
(config.globals as any).__TRANSFORM_HTML__ = true;
const transformed = tsJest.process(source, filePath, config) as string;
// ... finally the result of a `require('module-with-transformed-version')`
const exported = wrap(transformed)();
jestConfig = mockJestConfig(TEST_CASE);
const untransformed = tsJest.process(
fileContent,
`${jestConfig.rootDir}/${FILENAME}`,
jestConfig,
);
expect(untransformed).toBe(fileContent);
expect(untransformed).toMatchSnapshot('untransformed');

expect(exported).toMatchSnapshot('module');
// ... then the one which should be transformed
jestConfig = {
...mockJestConfig(TEST_CASE),
globals: { __TRANSFORM_HTML__: true },
};
const transformed = tsJest.process(
fileContent,
`${jestConfig.rootDir}/${FILENAME}`,
jestConfig,
) as string;
expect(transformed).not.toBe(fileContent);
expect(transformed).toMatchSnapshot('source');
expect(untransformed).toMatchSnapshot('untransformed');
// requiring the transformed version should return the same string as the untransformed version
expect(exported).toBe(untransformed);

// ... finally the result of a `require('module-with-transformed-version')`
const value = eval(
`(function(){const module={}; ${transformed}; return module.exports;})()`,
);
expect(value).toMatchSnapshot('module');
// the value should be the same string as the source version
expect(value).toBe(fileContent);
});
});

0 comments on commit fb5cd12

Please sign in to comment.