Skip to content

Commit

Permalink
Merge pull request #787 from huafu/fix-testing-utils
Browse files Browse the repository at this point in the history
Fix testing utils & cache digest & docs related to presets
  • Loading branch information
huafu committed Oct 6, 2018
2 parents 645558b + 89ad06a commit 90beca8
Show file tree
Hide file tree
Showing 33 changed files with 431 additions and 144 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -30,7 +30,7 @@ These instructions will get you setup to use `ts-jest` in your project. For more
| | using npm | using yarn |
|---:|---|---|
| **Prerequisites** | `npm i -D jest typescript` | `yarn add --dev jest typescript` |
| **Installing** | `npm i -D ts-jest` | `yarn add --dev ts-jest` |
| **Installing** | `npm i -D ts-jest @types/jest` | `yarn add --dev ts-jest @types/jest` |
| **Creating config** | `node_modules/.bin/ts-jest config:init` | `yarn ts-jest config:init` |
| **Running tests** | `npm t` or `node_modules/.bin/jest` | `yarn test` or `yarn jest` |

Expand Down
14 changes: 6 additions & 8 deletions docs/user/config/index.md
Expand Up @@ -54,20 +54,18 @@ module.exports = {

Any preset can also be used with other options.
If you're already using another preset, you might want only some specific settings from the chosen `ts-jest` preset.
In this case you'll need to use the JavaScript version of Jest config:
In this case you'll need to use the JavaScript version of Jest config (comment/uncomment according to your use-case):

```js
// jest.config.js
const tsJestPresets = require('ts-jest/presets');

const preset = tsJestPresets.defaults
// const preset = tsJestPresets.jsWithTs
// const preset = tsJestPresets.jsWithBabel
const { defaults: tsjPreset } = require('ts-jest/presets');
// const { jsWithTs: tsjPreset } = require('ts-jest/presets');
// const { jsWithBabel: tsjPreset } = require('ts-jest/presets');

module.exports = {
// [...]
transform: {
...preset.transform,
...tsjPreset.transform,
// [...]
}
}
Expand Down Expand Up @@ -133,7 +131,7 @@ module.exports = {

```js
// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest');
const { pathsToModuleNameMapper } = require('ts-jest/utils');
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig');
Expand Down
7 changes: 4 additions & 3 deletions docs/user/config/stringifyContentPathRegex.md
Expand Up @@ -18,16 +18,17 @@ In the `jest.config.js` version, you could do as in the `package.json` version o

```js
// jest.config.js
const { jestPreset } = require('ts-jest');
// Here `defaults` can be replaced with any other preset
const { defaults: tsjPreset } = require('ts-jest/presets');

module.exports = {
// [...]
moduleFileExtensions: [
...jestPreset.moduleFileExtensions,
...tsjPreset.moduleFileExtensions,
'html'
],
transform: {
...jestPreset.transform,
...tsjPreset.transform,
'\\.html$': 'ts-jest'
}
globals: {
Expand Down
6 changes: 3 additions & 3 deletions docs/user/install.md
Expand Up @@ -13,15 +13,15 @@ You can install `ts-jest` and dependencies all at once with the following comman
Using `npm`:

```sh
npm install --save-dev jest typescript ts-jest
npm install --save-dev jest typescript ts-jest @types/jest
```

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

Using `yarn`:

```sh
yarn add --dev jest typescript ts-jest
yarn add --dev jest typescript ts-jest @types/jest
```

</div></div>
Expand Down Expand Up @@ -55,7 +55,7 @@ yarn ts-jest config:init
This will create a basic Jest configuration file which will make Jest know about your `.ts` files and handle them correctly.

You can also use the `jest --init` command (prefixed with either `npx` or `yarn` depending on what you're using) to have more options related to Jest.
However, answer `no` to the Jest question about whether or not to enable Typescript. Instead, add the line: `preset: "ts-jest"` to the the `jest.config.js` file afterwards.
However, answer `no` to the Jest question about whether or not to enable Typescript. Instead, add the line: `preset: "ts-jest"` to the `jest.config.js` file afterwards.

### Customizing

Expand Down
6 changes: 3 additions & 3 deletions docs/user/react-native/index.md
Expand Up @@ -25,13 +25,13 @@ In the same way that you moved Babel config, move Jest config from `jest` key of

```js
// jest.config.js
const { jestPreset: tsJest } = require('ts-jest');
const { defaults: tsjPreset } = require('ts-jest/presets');

module.exports = {
...tsJest,
...tsjPreset,
preset: 'react-native',
transform: {
...tsJest.transform,
...tsjPreset.transform,
'\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
},
globals: {
Expand Down
2 changes: 1 addition & 1 deletion docs/user/test-helpers.md
Expand Up @@ -27,7 +27,7 @@ export const foo = {

```ts
// foo.spec.ts
import { mocked } from 'ts-jest'
import { mocked } from 'ts-jest/utils'
import { foo } from './foo'
jest.mock('./foo')

Expand Down
2 changes: 1 addition & 1 deletion e2e/__cases__/deep/src/Tests/jest.config.js
@@ -1,7 +1,7 @@
const cfg = {}

if (require('jest/package.json').version.split('.').shift() === '22') {
Object.assign(cfg, require('ts-jest').jestPreset)
Object.assign(cfg, require('ts-jest/presets').defaults)
} else {
cfg.preset = 'ts-jest'
}
Expand Down
9 changes: 9 additions & 0 deletions e2e/__cases__/test-helpers/deprecated.spec.ts
@@ -0,0 +1,9 @@
import { mocked } from 'ts-jest'
import { foo } from './to-mock'
jest.mock('./to-mock')

test('foo', () => {
foo()
// it should log that the helper moved
expect(mocked(foo).mock.calls.length).toBe(1)
})
2 changes: 1 addition & 1 deletion e2e/__cases__/test-helpers/fail.spec.ts
@@ -1,4 +1,4 @@
import { mocked } from 'ts-jest'
import { mocked } from 'ts-jest/utils'
import { foo, bar } from './to-mock'
jest.mock('./to-mock')

Expand Down
2 changes: 1 addition & 1 deletion e2e/__cases__/test-helpers/pass.spec.ts
@@ -1,4 +1,4 @@
import { mocked } from 'ts-jest'
import { mocked } from 'ts-jest/utils'
import { foo, bar } from './to-mock'
jest.mock('./to-mock')

Expand Down
4 changes: 2 additions & 2 deletions e2e/__templates__/with-jest-22/jest.config.js
@@ -1,6 +1,6 @@
const { jestPreset } = require('ts-jest')
const presets = require('ts-jest/presets')

module.exports = Object.assign({}, jestPreset, {
module.exports = Object.assign({}, presets.defaults, {
testEnvironment: 'node',
globals: { 'ts-jest': { tsConfig: {} } },
})
38 changes: 36 additions & 2 deletions e2e/__tests__/__snapshots__/test-helpers.test.ts.snap
Expand Up @@ -20,8 +20,42 @@ exports[`test-helpers 1`] = `
9 expect(mocked(bar, true).dummy.deep.deeper(42)).toBeUndefined()
~~
Test Suites: 1 failed, 1 passed, 2 total
Tests: 2 passed, 2 total
ts-jest[root] (WARN) The \`mocked\` helper has been moved to \`ts-jest/utils\`. Use \`import { mocked } from 'ts-jest/utils'\` instead.
PASS ./deprecated.spec.ts
Test Suites: 1 failed, 2 passed, 3 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
================================================================================
`;

exports[`with esModuleInterop set to false 1`] = `
× jest --no-cache
↳ exit code: 1
===[ STDOUT ]===================================================================
===[ STDERR ]===================================================================
PASS ./pass.spec.ts
FAIL ./fail.spec.ts
● Test suite failed to run
TypeScript diagnostics (customize using \`[jest-config].globals.ts-jest.diagnostics\` option):
fail.spec.ts:7:10 - error TS2554: Expected 0 arguments, but got 1.
7 expect(mocked(foo)('hello')).toBeUndefined()
~~~~~~~~~~~~~~~~~~~~
fail.spec.ts:9:46 - error TS2345: Argument of type '42' is not assignable to parameter of type 'string'.
9 expect(mocked(bar, true).dummy.deep.deeper(42)).toBeUndefined()
~~
ts-jest[root] (WARN) The \`mocked\` helper has been moved to \`ts-jest/utils\`. Use \`import { mocked } from 'ts-jest/utils'\` instead.
PASS ./deprecated.spec.ts
Test Suites: 1 failed, 2 passed, 3 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: XXs
Ran all test suites.
Expand Down
8 changes: 8 additions & 0 deletions e2e/__tests__/test-helpers.test.ts
Expand Up @@ -4,3 +4,11 @@ test('test-helpers', () => {
const test = configureTestCase('test-helpers', { noCache: true })
expect(test.run(1)).toMatchSnapshot()
})

test('with esModuleInterop set to false', () => {
const test = configureTestCase('test-helpers', {
noCache: true,
tsJestConfig: { tsConfig: { esModuleInterop: false, allowSyntheticDefaultImports: false } },
})
expect(test.run(1)).toMatchSnapshot()
})
29 changes: 15 additions & 14 deletions src/cli/cli.spec.ts
@@ -1,7 +1,7 @@
import * as _fs from 'fs'
import { normalize, resolve } from 'path'

import { mocked } from '../..'
import { mocked } from '../../utils'
import { logTargetMock, mockObject, mockWriteStream } from '../__helpers__/mocks'

import { processArgv } from '.'
Expand All @@ -10,23 +10,22 @@ import { processArgv } from '.'
jest.mock('fs')

const fs = mocked(_fs)
const logTarget = logTargetMock()
let lastExitCode: number | undefined

const runCli = async (
...args: any[]
): Promise<{ stdout: string; stderr: string; exitCode: number | undefined; log: string }> => {
mockedProcess.stderr.clear()
mockedProcess.stdout.clear()
logTarget.clear()
logTargetMock().clear()
mockedProcess.argv.splice(2, mockedProcess.argv.length - 2, ...args)
lastExitCode = undefined
await processArgv()
return {
exitCode: lastExitCode,
stdout: mockedProcess.stdout.written.join('\n'),
stderr: mockedProcess.stderr.written.join('\n'),
log: logTarget.lines.join('\n'),
log: logTargetMock().lines.join('\n'),
}
}

Expand Down Expand Up @@ -55,7 +54,7 @@ beforeEach(() => {
fs.writeFileSync.mockClear()
fs.existsSync.mockClear()
fs.readFileSync.mockClear()
logTarget.clear()
logTargetMock().clear()
})
afterEach(() => {
mockedProcess.mockRestore()
Expand Down Expand Up @@ -112,12 +111,13 @@ describe('config', async () => {
const noOption = ['config:init']
const fullOptions = [
...noOption,
'--babel',
'--tsconfig',
'tsconfig.test.json',
'--jsdom',
'--no-jest-preset',
'--allow-js',
'--js',
'ts',
'--babel',
]
it('should create a jest.config.json (without options)', async () => {
expect.assertions(2)
Expand Down Expand Up @@ -154,10 +154,10 @@ Jest configuration written to "${normalize('/foo/bar/jest.config.foo.js')}".
expect(fs.writeFileSync.mock.calls).toEqual([
[
normalize('/foo/bar/jest.config.foo.js'),
`const tsJest = require('ts-jest').createJestPreset({ allowJs: true });
`const { jsWithTs: tsjPreset } = require('ts-jest/presets');
module.exports = {
...tsJest,
...tsjPreset,
globals: {
'ts-jest': {
tsconfig: 'tsconfig.test.json',
Expand Down Expand Up @@ -198,8 +198,7 @@ Jest configuration written to "${normalize('/foo/bar/package.json')}".
const res = await runCli(...fullOptions, 'package.json')
expect(res).toEqual({
exitCode: 0,
log: `[level:20] creating jest presets handling JavaScript files
`,
log: '',
stderr: `
Jest configuration written to "${normalize('/foo/bar/package.json')}".
`,
Expand Down Expand Up @@ -259,10 +258,11 @@ Arguments:
Options:
--force Discard any existing Jest config
--allow-js ts-jest will be used to process JS files as well
--js ts|babel Process .js files with ts-jest if 'ts' or with
babel-jest if 'babel'
--no-jest-preset Disable the use of Jest presets
--tsconfig <file> Path to the tsconfig.json file
--babel Call BabelJest after ts-jest
--babel Pipe babel-jest after ts-jest
--jsdom Use jsdom as test environment instead of node
",
}
Expand Down Expand Up @@ -550,7 +550,8 @@ Arguments:
the \\"jest\\" property.
Options:
--allow-js ts-jest will be used to process JS files as well
--js ts|babel Process .js files with ts-jest if 'ts' or with
babel-jest if 'babel'
--no-jest-preset Disable the use of Jest presets
",
}
Expand Down

0 comments on commit 90beca8

Please sign in to comment.