Skip to content

Commit

Permalink
feat: hoisting + tests + many other things
Browse files Browse the repository at this point in the history
  • Loading branch information
huafu committed Aug 10, 2018
1 parent 2dba4fc commit 6186e84
Show file tree
Hide file tree
Showing 31 changed files with 519 additions and 616 deletions.
6 changes: 2 additions & 4 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
# TypeScript source code
src

# Tests
tests
e2e
test

# Developement scripts
scripts
Expand Down
14 changes: 0 additions & 14 deletions e2e/__cases__/hoisting/Hello.spec.ts

This file was deleted.

3 changes: 0 additions & 3 deletions e2e/__cases__/hoisting/Hello.ts

This file was deleted.

13 changes: 13 additions & 0 deletions e2e/__cases__/hoisting/hello.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import hello from './hello';

jest.mock('./hello');

describe('hello', () => {
const original = require.requireActual('./hello').default;
it('should have been mocked', () => {
const msg = hello();
expect(hello).not.toBe(original);
expect(msg).toBeUndefined();
expect(hello).toHaveProperty('mock');
});
});
3 changes: 3 additions & 0 deletions e2e/__cases__/hoisting/hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function() {
return 'hi!';
}
71 changes: 35 additions & 36 deletions e2e/__helpers__/test-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,37 @@ import { join } from 'path';
import * as Paths from '../../scripts/paths';
import * as fs from 'fs-extra';

const jestDescribe = describe;
const jestIt = it;
const jestExpect = expect;

const TEMPLATE_EXCLUDED_ITEMS = ['node_modules', 'package-lock.json'];

type RunWithTemplatesIterator = (
runtTest: () => TestRunResult,
templateName: string,
context: RunWithTemplateIteratorContext,
) => void;
interface RunWithTemplatesOptions {
iterator?: RunWithTemplatesIterator;
logUnlessStatus?: number;
}
interface WithTemplatesIteratorOptions {
describe?: string | false;
it?: string;
expect?: RunWithTemplatesIterator;

interface RunWithTemplateIteratorContext {
templateName: string;
describeLabel: string;
itLabel: string;
testLabel: string;
}

export function withTemplatesIterator({
describe = 'with template "__TEMPLATE_NAME__"',
it = 'should run as expected',
expect = runTest => {
jestExpect(runTest()).toMatchSnapshot();
},
}: WithTemplatesIteratorOptions = {}): RunWithTemplatesIterator {
return (runTest, name) => {
const interpolate = (msg: string) => msg.replace('__TEMPLATE_NAME__', name);
if (describe) {
jestDescribe(interpolate(describe), () => {
jestIt(interpolate(it), () => expect(runTest, name));
});
} else {
jestIt(interpolate(it), () => expect(runTest, name));
function createIteratorContext(
templateName: string,
expectedStatus?: number,
): RunWithTemplateIteratorContext {
const actionForExpectedStatus = (status?: number): string => {
if (status == null) {
return 'run';
}
return status === 0 ? 'pass' : 'fail';
};
return {
templateName,
describeLabel: `with template "${templateName}"`,
itLabel: `should ${actionForExpectedStatus(expectedStatus)}`,
testLabel: `should ${actionForExpectedStatus(
expectedStatus,
)} using template "${templateName}"`,
};
}

Expand Down Expand Up @@ -94,13 +89,15 @@ class TestCaseRunDescriptor {

runWithTemplates<T extends string>(
templates: T[],
{ iterator, logUnlessStatus }: RunWithTemplatesOptions = {},
expectedStatus?: number,
iterator?: RunWithTemplatesIterator,
): TestRunResultsMap<T> {
if (templates.length < 1) {
throw new RangeError(
`There must be at least one template to run the test case with.`,
);
}

if (!templates.every((t, i) => templates.indexOf(t, i + 1) === -1)) {
throw new Error(
`Each template must be unique. Given ${templates.join(', ')}`,
Expand All @@ -113,12 +110,12 @@ class TestCaseRunDescriptor {
template,
});
const runTest = () => {
const out = desc.run(logUnlessStatus);
const out = desc.run(expectedStatus);
map[template] = { ...out };
return out;
};
if (iterator) {
iterator(runTest, template);
iterator(runTest, createIteratorContext(template, expectedStatus));
} else {
runTest();
}
Expand Down Expand Up @@ -151,7 +148,7 @@ export type TestRunResultsMap<T extends string = string> = {
[key in T]: TestRunResult
};

export default function configureTestCase(
export function configureTestCase(
name: string,
options: RunTestOptions = {},
): TestCaseRunDescriptor {
Expand Down Expand Up @@ -246,17 +243,19 @@ function stripAnsiColors(stringToStrip: string): string {

function prepareTest(name: string, template: string): string {
const sourceDir = join(Paths.e2eSourceDir, name);
// working directory is in the temp directory, different for each tempalte name
// working directory is in the temp directory, different for each template name
const caseDir = join(Paths.e2eWorkDir, template, name);
const templateDir = join(Paths.e2eWorkTemplatesDir, template);

// ensure directory exists
// recreate the directory
fs.removeSync(caseDir);
fs.mkdirpSync(caseDir);

// link the node_modules dir if the template has
const tmplModulesDir = join(templateDir, 'node_modules');
const caseModulesDir = join(caseDir, 'node_modules');
if (!fs.existsSync(caseModulesDir) && fs.existsSync(tmplModulesDir)) {

// link the node_modules dir if the template has one
if (fs.existsSync(tmplModulesDir)) {
fs.symlinkSync(tmplModulesDir, caseModulesDir);
}

Expand Down
2 changes: 1 addition & 1 deletion e2e/__templates__/with-babel-7/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ module.exports = {
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
moduleFileExtensions: ['ts', 'js'],
testEnvironment: 'node',
globals: { 'ts-jest': { tsConfig: {} } },
globals: { 'ts-jest': { tsConfig: {}, useBabelJest: true } },
};
69 changes: 69 additions & 0 deletions e2e/__tests__/__snapshots__/hoisting.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Hoisting test with template "default" should pass 1`] = `
jest exit code: 0
===[ STDOUT ]===================================================================
===[ STDERR ]===================================================================
PASS ./hello.spec.ts
hello
√ should have been mocked
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
================================================================================
`;

exports[`Hoisting test with template "with-babel-6" should pass 1`] = `
jest exit code: 0
===[ STDOUT ]===================================================================
===[ STDERR ]===================================================================
PASS ./hello.spec.ts
hello
√ should have been mocked
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
================================================================================
`;

exports[`Hoisting test with template "with-babel-7" should pass 1`] = `
jest exit code: 0
===[ STDOUT ]===================================================================
===[ STDERR ]===================================================================
PASS ./hello.spec.ts
hello
√ should have been mocked
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
================================================================================
`;

exports[`Hoisting test with template "with-jest-22" should pass 1`] = `
jest exit code: 0
===[ STDOUT ]===================================================================
===[ STDERR ]===================================================================
PASS ./hello.spec.ts
hello
√ should have been mocked
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
================================================================================
`;
20 changes: 20 additions & 0 deletions e2e/__tests__/hoisting.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { configureTestCase } from '../__helpers__/test-case';
import { allPackageSets } from '../__helpers__/templates';

describe('Hoisting test', () => {
const testCase = configureTestCase('hoisting', { args: ['--no-cache'] });

testCase.runWithTemplates(
allPackageSets,
0,
(runTest, { describeLabel, itLabel }) => {
describe(describeLabel, () => {
it(itLabel, () => {
const result = runTest();
expect(result.status).toBe(0);
expect(result).toMatchSnapshot();
});
});
},
);
});
13 changes: 0 additions & 13 deletions e2e/__tests__/simple.spec.ts

This file was deleted.

20 changes: 20 additions & 0 deletions e2e/__tests__/simple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { configureTestCase } from '../__helpers__/test-case';
import { allPackageSets } from '../__helpers__/templates';

describe('Simple test', () => {
const testCase = configureTestCase('simple', { args: ['--no-cache'] });

testCase.runWithTemplates(
allPackageSets,
0,
(runTest, { describeLabel, itLabel }) => {
describe(describeLabel, () => {
it(itLabel, () => {
const result = runTest();
expect(result.status).toBe(0);
expect(result).toMatchSnapshot();
});
});
},
);
});
31 changes: 0 additions & 31 deletions e2e/__tests__/source-map.spec.ts

This file was deleted.

43 changes: 43 additions & 0 deletions e2e/__tests__/source-map.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { configureTestCase } from '../__helpers__/test-case';
import { allPackageSets } from '../__helpers__/templates';

describe('Source maps', () => {
describe('console.log()', () => {
const testCase = configureTestCase('source-maps', { args: ['--no-cache'] });

testCase.runWithTemplates(
allPackageSets,
0,
(runTest, { describeLabel }) => {
describe(describeLabel, () => {
it('should pass reporting correct line number', () => {
const result = runTest();
expect(result.status).toBe(0);
expect(result).toMatchSnapshot();
});
});
},
);
});

describe('throw new Error()', () => {
const testCase = configureTestCase('source-maps', {
args: ['--no-cache'],
env: { __FORCE_FAIL: '1' },
});

testCase.runWithTemplates(
allPackageSets,
1,
(runTest, { describeLabel }) => {
describe(describeLabel, () => {
it('should fail reporting correct line number', () => {
const result = runTest();
expect(result.status).toBe(1);
expect(result).toMatchSnapshot();
});
});
},
);
});
});
10 changes: 10 additions & 0 deletions e2e/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
transform: {
'\\.ts$': '<rootDir>/../dist/index.js',
},
testRegex: '/__tests__/.+\\.test\\.ts$',
collectCoverageFrom: ['<rootDir>/../src/**/*.ts'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
testEnvironment: 'node',
snapshotSerializers: ['<rootDir>/__serializers__/test-run-result.ts'],
};
Loading

0 comments on commit 6186e84

Please sign in to comment.