Skip to content

Commit

Permalink
feat: io serializer + other test utils
Browse files Browse the repository at this point in the history
  • Loading branch information
huafu committed Aug 21, 2018
1 parent 6a7f01f commit d03e0e7
Show file tree
Hide file tree
Showing 20 changed files with 659 additions and 142 deletions.
16 changes: 8 additions & 8 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Tests
e2e/
e2e

# sources are inlined
src/
src

# Developement scripts
scripts/
scripts

# Logs
logs
Expand All @@ -24,7 +24,7 @@ pids
lib-cov

# Coverage directory used by tools like istanbul
coverage/
coverage

# nyc test coverage
.nyc_output
Expand All @@ -39,15 +39,15 @@ coverage/
build/Release

# Dependency directories
node_modules/
jspm_packages/
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history
# while refactoring...
old/
old

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

afterAll(() => {
// this should go after
jest.unmock('./hello');
})

jest.mock('./hello');

describe('hello', () => {
Expand All @@ -9,5 +14,7 @@ describe('hello', () => {
expect(hello).not.toBe(original);
expect(msg).toBeUndefined();
expect(hello).toHaveProperty('mock');
expect(require('foo')).toBe('bar');
jest.mock('foo', () => 'bar', { virtual: true });
});
});
49 changes: 40 additions & 9 deletions e2e/__helpers__/test-case.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// tslint:disable-file:no-shadowed-variable
import { sync as spawnSync } from 'cross-spawn'
import { join, relative, sep } from 'path'
import { join, relative, sep, isAbsolute } from 'path'
import * as Paths from '../../scripts/lib/paths'
import * as fs from 'fs-extra'
import { RawSourceMap } from 'source-map'
import { relativiseSourceRoot, extractSourceMaps } from './source-maps'
import { extractSourceMaps } from './source-maps'
import { SpawnSyncReturns } from 'child_process'
import merge from 'lodash.merge'
import { TsJestConfig } from '../../src/lib/types'
import { rewriteSourceMaps, relativisePaths } from '../../src/__helpers__/source-maps'

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

Expand Down Expand Up @@ -144,35 +145,57 @@ export class TestRunResult {
constructor(
readonly cwd: string,
readonly result: SpawnSyncReturns<Buffer>,
readonly ioDir?: string,
readonly context: Readonly<{
ioDir?: string | undefined,
cmd: string,
args: string[],
env: { [key: string]: string },
}>,
) { }
get isPass() { return this.status === 0 }
get isFail() { return !this.isPass }
get status() { return this.result.status }
get output() { return stripAnsiColors((this.result.output ? this.result.output.join('\n\n') : '')) }
get stderr() { return stripAnsiColors((this.result.stderr || '').toString()) }
get stdout() { return stripAnsiColors((this.result.stdout || '').toString()) }
get cmdLine() {
return [this.context.cmd, ...this.context.args].join(' ')
}
ioFor(relFilePath: string): TestFileIo {
if (!this.ioDir) {
if (!this.context.ioDir) {
throw new Error('IO not written for test, you must configure the test with `writeIo: true`.')
}
const io = require(`${this.ioDir}/${relFilePath}.json`)
return new TestFileIo(this.cwd, io.in, io.out)
const io = require(`${this.context.ioDir}/${relFilePath}.json`)
return new TestFileIo(this.cwd, relFilePath, io.in, io.out)
}
}

// tslint:disable-next-line:max-classes-per-file
class TestFileIo {
export class TestFileIo {
constructor(
private _cwd: string,
readonly filename: string,
readonly input: [string, jest.Path, jest.ProjectConfig, jest.TransformOptions?],
readonly output: string | jest.TransformedSource,
) { }
get inputCode(): string { return this.input[0] }
get inputPath(): string { return this.input[1] }
get outputCode(): string { return typeof this.output === 'object' ? this.output.code : this.output }
get outputSourceMaps(): RawSourceMap | undefined { return extractSourceMaps(this.outputCode) }
get normalizedOutputCode(): string { return relativiseSourceRoot(this._cwd, this.outputCode, '<cwd>/') }
get normalizedOutputCode(): string {
return rewriteSourceMaps(
this.outputCode,
this.sourceMapsNormalizer,
)
}
get normalizedOutputSourceMaps(): RawSourceMap | undefined {
const maps = this.outputSourceMaps
if (maps) return this.sourceMapsNormalizer(maps)
return
}
get sourceMapsNormalizer() {
return (maps: RawSourceMap): RawSourceMap => relativisePaths(maps, this._cwd, '<cwd>/')
}
}

// tslint:disable-next-line:interface-over-type-literal
Expand Down Expand Up @@ -240,6 +263,7 @@ export function run(name: string, options: RunTestOptions = {}): TestRunResult {
)
const pkg = require(join(dir, 'package.json'))

let shortCmd: string
let cmdArgs: string[] = []
if (inject) {
cmdArgs.push('--testPathPattern="/__eval\\\\.ts$"')
Expand All @@ -253,8 +277,10 @@ export function run(name: string, options: RunTestOptions = {}): TestRunResult {
cmdArgs.unshift('--')
}
cmdArgs = ['npm', '-s', 'run', 'test', ...cmdArgs]
shortCmd = 'npm'
} else {
cmdArgs.unshift(join(dir, 'node_modules', '.bin', 'jest'))
shortCmd = 'jest'
}

// merge given config extend
Expand Down Expand Up @@ -316,7 +342,12 @@ export function run(name: string, options: RunTestOptions = {}): TestRunResult {
})
})

return new TestRunResult(fs.realpathSync(dir), result, writeIo ? ioDir : undefined)
return new TestRunResult(fs.realpathSync(dir), result, {
cmd: shortCmd,
args: cmdArgs,
env: mergedEnv,
ioDir: writeIo ? ioDir : undefined,
})
}

// from https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
Expand Down
19 changes: 19 additions & 0 deletions e2e/__serializers__/test-file-io.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { TestFileIo } from '../__helpers__/test-case'
import { safeDump } from 'js-yaml'

export const test = (val: any) => val && val instanceof TestFileIo
export const print = (val: TestFileIo, serialize: any, indent: any) => {
const sourceMaps = val.normalizedOutputSourceMaps
const out = [
`===[ FILE: ${val.filename.replace(/\\/g, '/')} ]${'='.repeat(67 - val.filename.length)}`,
val.normalizedOutputCode,
...(sourceMaps ? [
`===[ INLINE SOURCE MAPS ]${'='.repeat(55)}`,
safeDump(sourceMaps, {sortKeys: true, noRefs: true, noCompatMode: true}).trim(),
] : []),
'='.repeat(80),
]
.map(l => indent(l))
.join('\n')
return `${out}`
}
4 changes: 3 additions & 1 deletion e2e/__serializers__/test-run-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
export const test = (val: any) => val && val instanceof TestRunResult
export const print = (val: TestRunResult, serialize: any, indent: any) => {
const out = [
`${val.status === 0 ? '√' : '×'} ${val.cmdLine}`,
`↳ exit code: ${val.status}`,
`===[ STDOUT ]${'='.repeat(67)}`,
sanitizeOutput(val.stdout),
`===[ STDERR ]${'='.repeat(67)}`,
Expand All @@ -14,5 +16,5 @@ export const print = (val: TestRunResult, serialize: any, indent: any) => {
]
.map(l => indent(l))
.join('\n')
return `jest exit code: ${val.status}\n${out}`
return out
}
Loading

0 comments on commit d03e0e7

Please sign in to comment.