From a9fb41b6f0d8dea438774a026ee93be1317f0a6f Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sat, 23 Feb 2019 21:12:12 +0500 Subject: [PATCH 01/25] Migration to ts (part 1) --- ...ectationFailed.js => ExpectationFailed.ts} | 2 - .../src/{PCancelable.js => PCancelable.ts} | 9 ++- .../src/__tests__/hooksError.test.js | 2 - ...rorMessage.js => assertionErrorMessage.ts} | 38 ++++++------- .../jest-jasmine2/src/{each.js => each.ts} | 7 +-- .../{errorOnPrivate.js => errorOnPrivate.ts} | 12 ++-- ...Factory.js => expectationResultFactory.ts} | 14 ++--- .../jest-jasmine2/src/{index.js => index.ts} | 31 +++++----- .../src/{isError.js => isError.ts} | 2 - .../{CallTracker.js => CallTracker.ts} | 1 - .../src/jasmine/{Env.js => Env.ts} | 0 .../{JsApiReporter.js => JsApiReporter.ts} | 1 - ...eportDispatcher.js => ReportDispatcher.ts} | 1 - .../src/jasmine/{Spec.js => Spec.ts} | 1 - .../{SpyStrategy.js => SpyStrategy.ts} | 0 .../src/jasmine/{Suite.js => Suite.ts} | 1 - .../src/jasmine/{Timer.js => Timer.ts} | 26 +++++---- .../jasmine/{createSpy.js => createSpy.ts} | 0 .../{jasmineLight.js => jasmineLight.ts} | 10 ++-- .../{spyRegistry.js => spyRegistry.ts} | 1 - ...AsyncInstall.js => jasmineAsyncInstall.ts} | 12 ++-- .../src/{jestExpect.js => jestExpect.ts} | 19 ++++--- .../src/{pTimeout.js => pTimeout.ts} | 2 - .../src/{queueRunner.js => queueRunner.ts} | 20 +++---- .../src/{reporter.js => reporter.ts} | 56 ++++++++----------- ..._jest_globals.js => setup_jest_globals.ts} | 51 ++++++++--------- .../{treeProcessor.js => treeProcessor.ts} | 34 ++++++----- packages/jest-jasmine2/src/types.ts | 39 +++++++++++++ 28 files changed, 198 insertions(+), 194 deletions(-) rename packages/jest-jasmine2/src/{ExpectationFailed.js => ExpectationFailed.ts} (95%) rename packages/jest-jasmine2/src/{PCancelable.js => PCancelable.ts} (88%) rename packages/jest-jasmine2/src/{assertionErrorMessage.js => assertionErrorMessage.ts} (84%) rename packages/jest-jasmine2/src/{each.js => each.ts} (86%) rename packages/jest-jasmine2/src/{errorOnPrivate.js => errorOnPrivate.ts} (88%) rename packages/jest-jasmine2/src/{expectationResultFactory.js => expectationResultFactory.ts} (93%) rename packages/jest-jasmine2/src/{index.js => index.ts} (89%) rename packages/jest-jasmine2/src/{isError.js => isError.ts} (98%) rename packages/jest-jasmine2/src/jasmine/{CallTracker.js => CallTracker.ts} (99%) rename packages/jest-jasmine2/src/jasmine/{Env.js => Env.ts} (100%) rename packages/jest-jasmine2/src/jasmine/{JsApiReporter.js => JsApiReporter.ts} (99%) rename packages/jest-jasmine2/src/jasmine/{ReportDispatcher.js => ReportDispatcher.ts} (99%) rename packages/jest-jasmine2/src/jasmine/{Spec.js => Spec.ts} (99%) rename packages/jest-jasmine2/src/jasmine/{SpyStrategy.js => SpyStrategy.ts} (100%) rename packages/jest-jasmine2/src/jasmine/{Suite.js => Suite.ts} (99%) rename packages/jest-jasmine2/src/jasmine/{Timer.js => Timer.ts} (80%) rename packages/jest-jasmine2/src/jasmine/{createSpy.js => createSpy.ts} (100%) rename packages/jest-jasmine2/src/jasmine/{jasmineLight.js => jasmineLight.ts} (96%) rename packages/jest-jasmine2/src/jasmine/{spyRegistry.js => spyRegistry.ts} (99%) rename packages/jest-jasmine2/src/{jasmineAsyncInstall.js => jasmineAsyncInstall.ts} (96%) rename packages/jest-jasmine2/src/{jestExpect.js => jestExpect.ts} (83%) rename packages/jest-jasmine2/src/{pTimeout.js => pTimeout.ts} (98%) rename packages/jest-jasmine2/src/{queueRunner.js => queueRunner.ts} (85%) rename packages/jest-jasmine2/src/{reporter.js => reporter.ts} (81%) rename packages/jest-jasmine2/src/{setup_jest_globals.js => setup_jest_globals.ts} (72%) rename packages/jest-jasmine2/src/{treeProcessor.js => treeProcessor.ts} (75%) create mode 100644 packages/jest-jasmine2/src/types.ts diff --git a/packages/jest-jasmine2/src/ExpectationFailed.js b/packages/jest-jasmine2/src/ExpectationFailed.ts similarity index 95% rename from packages/jest-jasmine2/src/ExpectationFailed.js rename to packages/jest-jasmine2/src/ExpectationFailed.ts index 2469c8143a28..ad9910ff3e9e 100644 --- a/packages/jest-jasmine2/src/ExpectationFailed.js +++ b/packages/jest-jasmine2/src/ExpectationFailed.ts @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ export default class ExpectationFailed extends Error {} diff --git a/packages/jest-jasmine2/src/PCancelable.js b/packages/jest-jasmine2/src/PCancelable.ts similarity index 88% rename from packages/jest-jasmine2/src/PCancelable.js rename to packages/jest-jasmine2/src/PCancelable.ts index deadee0fbd03..9a6e9eb37451 100644 --- a/packages/jest-jasmine2/src/PCancelable.js +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -1,6 +1,9 @@ -// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. - -'use strict'; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ class CancelError extends Error { constructor() { diff --git a/packages/jest-jasmine2/src/__tests__/hooksError.test.js b/packages/jest-jasmine2/src/__tests__/hooksError.test.js index 020c5f111e82..6f6ca1e87f81 100644 --- a/packages/jest-jasmine2/src/__tests__/hooksError.test.js +++ b/packages/jest-jasmine2/src/__tests__/hooksError.test.js @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ 'use strict'; diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.js b/packages/jest-jasmine2/src/assertionErrorMessage.ts similarity index 84% rename from packages/jest-jasmine2/src/assertionErrorMessage.js rename to packages/jest-jasmine2/src/assertionErrorMessage.ts index dd83b4cee4a8..5fcb42bbb383 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.js +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -3,34 +3,32 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -// TODO: Converted to TS. It's also not exported, but should be imported from `matcher-utils` -import type {DiffOptions} from 'jest-diff'; - import {diff, printReceived, printExpected} from 'jest-matcher-utils'; import chalk from 'chalk'; -type AssertionError = {| - actual: ?string, - expected: ?string, - generatedMessage: boolean, - message: string, - name: string, - operator: ?string, - stack: string, -|}; - -const assertOperatorsMap = { +// TODO replace with import {DiffOptions} from 'jest-matcher-utils'; +type DiffOptions = Parameters[2]; + +type AssertionError = { + actual: string | null; + expected: string | null; + generatedMessage: boolean; + message: string; + name: string; + operator: string | null; + stack: string; +}; + +const assertOperatorsMap: {[key: string]: string} = { '!=': 'notEqual', '!==': 'notStrictEqual', '==': 'equal', '===': 'strictEqual', }; -const humanReadableOperators = { +const humanReadableOperators: {[key: string]: string} = { deepEqual: 'to deeply equal', deepStrictEqual: 'to deeply and strictly equal', equal: 'to be equal', @@ -41,7 +39,7 @@ const humanReadableOperators = { strictEqual: 'to strictly be equal', }; -const getOperatorName = (operator: ?string, stack: string) => { +const getOperatorName = (operator: string | null, stack: string) => { if (typeof operator === 'string') { return assertOperatorsMap[operator] || operator; } @@ -54,7 +52,7 @@ const getOperatorName = (operator: ?string, stack: string) => { return ''; }; -const operatorMessage = (operator: ?string) => { +const operatorMessage = (operator: string | null) => { const niceOperatorName = getOperatorName(operator, ''); // $FlowFixMe: we default to the operator itself, so holes in the map doesn't matter const humanReadableOperator = humanReadableOperators[niceOperatorName]; @@ -70,7 +68,7 @@ const assertThrowingMatcherHint = (operatorName: string) => chalk.red('function') + chalk.dim(')'); -const assertMatcherHint = (operator: ?string, operatorName: string) => { +const assertMatcherHint = (operator: string | null, operatorName: string) => { let message = chalk.dim('assert') + chalk.dim('.' + operatorName + '(') + diff --git a/packages/jest-jasmine2/src/each.js b/packages/jest-jasmine2/src/each.ts similarity index 86% rename from packages/jest-jasmine2/src/each.js rename to packages/jest-jasmine2/src/each.ts index 23574b1cb302..22cde37e5166 100644 --- a/packages/jest-jasmine2/src/each.js +++ b/packages/jest-jasmine2/src/each.ts @@ -3,15 +3,12 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {Environment} from 'types/Environment'; - +import {Environment} from '@jest/types'; import {bind as bindEach} from 'jest-each'; -export default (environment: Environment): void => { +export default (environment: Environment.Environment): void => { environment.global.it.each = bindEach(environment.global.it); environment.global.fit.each = bindEach(environment.global.fit); environment.global.xit.each = bindEach(environment.global.xit); diff --git a/packages/jest-jasmine2/src/errorOnPrivate.js b/packages/jest-jasmine2/src/errorOnPrivate.ts similarity index 88% rename from packages/jest-jasmine2/src/errorOnPrivate.js rename to packages/jest-jasmine2/src/errorOnPrivate.ts index 2028628d4adc..9d2469252269 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.js +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -3,15 +3,13 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {Global} from '../../../types/Global'; +import {Global} from '@jest/types'; import {ErrorWithStack} from 'jest-util'; // prettier-ignore -const disabledGlobals = { +const disabledGlobals: {[key: string]: string} = { fail: 'Illegal usage of global `fail`, prefer throwing an error, or the `done.fail` callback.', pending: 'Illegal usage of global `pending`, prefer explicitly skipping a test using `test.skip`', spyOn: 'Illegal usage of global `spyOn`, prefer `jest.spyOn`.', @@ -19,7 +17,7 @@ const disabledGlobals = { }; // prettier-ignore -const disabledJasmineMethods = { +const disabledJasmineMethods: {[key: string]: string} = { addMatchers: 'Illegal usage of `jasmine.addMatchers`, prefer `expect.extends`.', any: 'Illegal usage of `jasmine.any`, prefer `expect.any`.', anything: 'Illegal usage of `jasmine.anything`, prefer `expect.anything`.', @@ -29,7 +27,7 @@ const disabledJasmineMethods = { stringMatching: 'Illegal usage of `jasmine.stringMatching`, prefer `expect.stringMatching`.', }; -export function installErrorOnPrivate(global: Global): void { +export function installErrorOnPrivate(global: Global.Global): void { const {jasmine} = global; Object.keys(disabledGlobals).forEach(functionName => { global[functionName] = () => { @@ -60,6 +58,6 @@ export function installErrorOnPrivate(global: Global): void { }); } -function throwAtFunction(message, fn) { +function throwAtFunction(message: string, fn: Function) { throw new ErrorWithStack(message, fn); } diff --git a/packages/jest-jasmine2/src/expectationResultFactory.js b/packages/jest-jasmine2/src/expectationResultFactory.ts similarity index 93% rename from packages/jest-jasmine2/src/expectationResultFactory.js rename to packages/jest-jasmine2/src/expectationResultFactory.ts index 2bd3b7c65dec..e4f7a3961a4a 100644 --- a/packages/jest-jasmine2/src/expectationResultFactory.js +++ b/packages/jest-jasmine2/src/expectationResultFactory.ts @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ import prettyFormat from 'pretty-format'; @@ -54,12 +52,12 @@ function stackFormatter(options, initError, errorMessage) { } type Options = { - matcherName: string, - passed: boolean, - actual?: any, - error?: any, - expected?: any, - message?: string, + matcherName: string; + passed: boolean; + actual?: any; + error?: any; + expected?: any; + message?: string; }; export default function expectationResultFactory( diff --git a/packages/jest-jasmine2/src/index.js b/packages/jest-jasmine2/src/index.ts similarity index 89% rename from packages/jest-jasmine2/src/index.js rename to packages/jest-jasmine2/src/index.ts index 78ae577ce84b..3c6f1625eed3 100644 --- a/packages/jest-jasmine2/src/index.js +++ b/packages/jest-jasmine2/src/index.ts @@ -3,32 +3,28 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {Environment} from 'types/Environment'; -import type {GlobalConfig, ProjectConfig} from 'types/Config'; -import type {SnapshotState} from 'jest-snapshot'; -import type {TestResult} from 'types/TestResult'; -import type Runtime from 'jest-runtime'; - import path from 'path'; +import {Environment, Config, TestResult} from '@jest/types'; +import {SnapshotState} from 'jest-snapshot'; +import Runtime from 'jest-runtime'; + +import {getCallsite} from 'jest-util'; import installEach from './each'; import {installErrorOnPrivate} from './errorOnPrivate'; -import {getCallsite} from 'jest-util'; import JasmineReporter from './reporter'; import jasmineAsyncInstall from './jasmineAsyncInstall'; const JASMINE = require.resolve('./jasmine/jasmineLight.js'); async function jasmine2( - globalConfig: GlobalConfig, - config: ProjectConfig, - environment: Environment, + globalConfig: Config.GlobalConfig, + config: Config.ProjectConfig, + environment: Environment.Environment, runtime: Runtime, testPath: string, -): Promise { +): Promise { const reporter = new JasmineReporter(globalConfig, config, testPath); const jasmineFactory = runtime.requireInternalModule(JASMINE); const jasmine = jasmineFactory.create({ @@ -137,7 +133,8 @@ async function jasmine2( }); } - const snapshotState: SnapshotState = runtime + // TODO: make just snapshotState: SnapshotState when `jest-snapshot` is ESM + const snapshotState: typeof SnapshotState.prototype = runtime .requireInternalModule(path.resolve(__dirname, './setup_jest_globals.js')) .default({ config, @@ -168,7 +165,11 @@ async function jasmine2( return addSnapshotData(results, snapshotState); } -const addSnapshotData = (results, snapshotState) => { +// TODO: make just snapshotState: SnapshotState when `jest-snapshot` is ESM +const addSnapshotData = ( + results: TestResult.TestResult, + snapshotState: typeof SnapshotState.prototype, +) => { results.testResults.forEach(({fullName, status}) => { if (status === 'pending' || status === 'failed') { // if test is skipped or failed, we don't want to mark diff --git a/packages/jest-jasmine2/src/isError.js b/packages/jest-jasmine2/src/isError.ts similarity index 98% rename from packages/jest-jasmine2/src/isError.js rename to packages/jest-jasmine2/src/isError.ts index 2ffab4c3c7ff..186bff452b0e 100644 --- a/packages/jest-jasmine2/src/isError.js +++ b/packages/jest-jasmine2/src/isError.ts @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ import prettyFormat from 'pretty-format'; diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.js b/packages/jest-jasmine2/src/jasmine/CallTracker.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/CallTracker.js rename to packages/jest-jasmine2/src/jasmine/CallTracker.ts index 3f676d118a05..9c8cf9a201c3 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.js +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ function CallTracker() { let calls = []; diff --git a/packages/jest-jasmine2/src/jasmine/Env.js b/packages/jest-jasmine2/src/jasmine/Env.ts similarity index 100% rename from packages/jest-jasmine2/src/jasmine/Env.js rename to packages/jest-jasmine2/src/jasmine/Env.ts diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.js b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/JsApiReporter.js rename to packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index 8919b695ab44..e3dc646a8022 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.js +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ /* eslint-disable sort-keys */ const noopTimer = { diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.js b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/ReportDispatcher.js rename to packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index aa1ed23997e7..d34b565f8de2 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.js +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ export default function ReportDispatcher(methods: Array) { const dispatchedMethods = methods || []; diff --git a/packages/jest-jasmine2/src/jasmine/Spec.js b/packages/jest-jasmine2/src/jasmine/Spec.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/Spec.js rename to packages/jest-jasmine2/src/jasmine/Spec.ts index fd729e0b2c80..b4fb2d8bb6e2 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.js +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ /* eslint-disable sort-keys */ import {AssertionError} from 'assert'; diff --git a/packages/jest-jasmine2/src/jasmine/SpyStrategy.js b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts similarity index 100% rename from packages/jest-jasmine2/src/jasmine/SpyStrategy.js rename to packages/jest-jasmine2/src/jasmine/SpyStrategy.ts diff --git a/packages/jest-jasmine2/src/jasmine/Suite.js b/packages/jest-jasmine2/src/jasmine/Suite.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/Suite.js rename to packages/jest-jasmine2/src/jasmine/Suite.ts index 758a16c32882..f8f2432903ae 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.js +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ /* eslint-disable sort-keys */ import {convertDescriptorToString} from 'jest-util'; diff --git a/packages/jest-jasmine2/src/jasmine/Timer.js b/packages/jest-jasmine2/src/jasmine/Timer.ts similarity index 80% rename from packages/jest-jasmine2/src/jasmine/Timer.js rename to packages/jest-jasmine2/src/jasmine/Timer.ts index be908df48185..a4ef52638082 100644 --- a/packages/jest-jasmine2/src/jasmine/Timer.js +++ b/packages/jest-jasmine2/src/jasmine/Timer.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ const defaultNow = (function(Date) { return function() { @@ -36,17 +35,22 @@ const defaultNow = (function(Date) { }; })(Date); -export default function Timer(options: Object) { - options = options || {}; +export default class Timer { + start: () => void; + elapsed: () => number; - const now = options.now || defaultNow; - let startTime; + constructor(options: {now?: () => number}) { + options = options || {}; - this.start = function() { - startTime = now(); - }; + const now = options.now || defaultNow; + let startTime: number; - this.elapsed = function() { - return now() - startTime; - }; + this.start = function() { + startTime = now(); + }; + + this.elapsed = function() { + return now() - startTime; + }; + } } diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.js b/packages/jest-jasmine2/src/jasmine/createSpy.ts similarity index 100% rename from packages/jest-jasmine2/src/jasmine/createSpy.js rename to packages/jest-jasmine2/src/jasmine/createSpy.ts diff --git a/packages/jest-jasmine2/src/jasmine/jasmineLight.js b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts similarity index 96% rename from packages/jest-jasmine2/src/jasmine/jasmineLight.js rename to packages/jest-jasmine2/src/jasmine/jasmineLight.ts index 341e4c211647..0aa19fe22b4d 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmineLight.js +++ b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts @@ -28,11 +28,9 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ /* eslint-disable sort-keys */ -import type {Jasmine} from 'types/Jasmine'; - +import {Jasmine} from '../types'; import createSpy from './createSpy'; import Env from './Env'; import JsApiReporter from './JsApiReporter'; @@ -42,7 +40,11 @@ import SpyRegistry from './spyRegistry'; import Suite from './Suite'; import Timer from './Timer'; -exports.create = function(createOptions: Object) { +type $J = { + _DEFAULT_TIMEOUT_INTERVAL: number; +}; + +exports.create = function(createOptions: Object): $J { const j$ = {...createOptions}; j$._DEFAULT_TIMEOUT_INTERVAL = 5000; diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.js b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts similarity index 99% rename from packages/jest-jasmine2/src/jasmine/spyRegistry.js rename to packages/jest-jasmine2/src/jasmine/spyRegistry.ts index b3e84c09cad2..cbd32354733a 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.js +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -28,7 +28,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ import CallTracker from './CallTracker'; diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.js b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts similarity index 96% rename from packages/jest-jasmine2/src/jasmineAsyncInstall.js rename to packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 1d296e53d232..9478ff1901a1 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.js +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ /** @@ -12,15 +10,13 @@ * returning a promise from `it/test` and `before/afterEach/All` blocks. */ -import type {Global} from 'types/Global'; -import type {GlobalConfig} from 'types/Config'; - +import {Global, Config} from '@jest/types'; import co from 'co'; import isGeneratorFn from 'is-generator-fn'; import throat from 'throat'; import isError from './isError'; -function isPromise(obj) { +function isPromise(obj: any) { return obj && typeof obj.then === 'function'; } @@ -153,8 +149,8 @@ function makeConcurrent(originalFn: Function, env, mutex) { } export default function jasmineAsyncInstall( - globalConfig: GlobalConfig, - global: Global, + globalConfig: Config.GlobalConfig, + global: Global.Global, ) { const jasmine = global.jasmine; const mutex = throat(globalConfig.maxConcurrency); diff --git a/packages/jest-jasmine2/src/jestExpect.js b/packages/jest-jasmine2/src/jestExpect.ts similarity index 83% rename from packages/jest-jasmine2/src/jestExpect.js rename to packages/jest-jasmine2/src/jestExpect.ts index f6f95bc19790..09062d6a3fbc 100644 --- a/packages/jest-jasmine2/src/jestExpect.js +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -3,12 +3,9 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {RawMatcherFn} from 'types/Matchers'; - +import {Matchers} from '@jest/types'; import expect from 'expect'; import { addSerializer, @@ -17,12 +14,14 @@ import { toThrowErrorMatchingSnapshot, toThrowErrorMatchingInlineSnapshot, } from 'jest-snapshot'; +import {RawMatcherFn} from './types'; type JasmineMatcher = { - (matchersUtil: any, context: any): JasmineMatcher, - compare: () => RawMatcherFn, - negativeCompare: () => RawMatcherFn, + (matchersUtil: any, context: any): JasmineMatcher; + compare: () => RawMatcherFn; + negativeCompare: () => RawMatcherFn; }; + type JasmineMatchersObject = {[id: string]: JasmineMatcher}; export default (config: {expand: boolean}) => { @@ -34,7 +33,7 @@ export default (config: {expand: boolean}) => { toThrowErrorMatchingInlineSnapshot, toThrowErrorMatchingSnapshot, }); - (expect: Object).addSnapshotSerializer = addSerializer; + expect.addSnapshotSerializer = addSerializer; const jasmine = global.jasmine; jasmine.anything = expect.anything; @@ -46,7 +45,9 @@ export default (config: {expand: boolean}) => { jasmine.addMatchers = (jasmineMatchersObject: JasmineMatchersObject) => { const jestMatchersObject = Object.create(null); Object.keys(jasmineMatchersObject).forEach(name => { - jestMatchersObject[name] = function(): RawMatcherFn { + jestMatchersObject[name] = function( + this: Matchers.MatcherState, + ): RawMatcherFn { // use "expect.extend" if you need to use equality testers (via this.equal) const result = jasmineMatchersObject[name](null, null); // if there is no 'negativeCompare', both should be handled by `compare` diff --git a/packages/jest-jasmine2/src/pTimeout.js b/packages/jest-jasmine2/src/pTimeout.ts similarity index 98% rename from packages/jest-jasmine2/src/pTimeout.js rename to packages/jest-jasmine2/src/pTimeout.ts index 6df9b31538d2..b4edafc439a4 100644 --- a/packages/jest-jasmine2/src/pTimeout.js +++ b/packages/jest-jasmine2/src/pTimeout.ts @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ // A specialized version of `p-timeout` that does not touch globals. diff --git a/packages/jest-jasmine2/src/queueRunner.js b/packages/jest-jasmine2/src/queueRunner.ts similarity index 85% rename from packages/jest-jasmine2/src/queueRunner.js rename to packages/jest-jasmine2/src/queueRunner.ts index e55108b66b18..10d91167ab79 100644 --- a/packages/jest-jasmine2/src/queueRunner.js +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -3,26 +3,24 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ import PCancelable from './PCancelable'; import pTimeout from './pTimeout'; type Options = { - clearTimeout: (timeoutID: number) => void, - fail: () => void, - onException: (error: Error) => void, - queueableFns: Array, - setTimeout: (func: () => void, delay: number) => number, - userContext: any, + clearTimeout: (timeoutID: number) => void; + fail: () => void; + onException: (error: Error) => void; + queueableFns: Array; + setTimeout: (func: () => void, delay: number) => number; + userContext: any; }; type QueueableFn = { - fn: (next: () => void) => void, - timeout?: () => number, - initError?: Error, + fn: (next: () => void) => void; + timeout?: () => number; + initError?: Error; }; export default function queueRunner(options: Options) { diff --git a/packages/jest-jasmine2/src/reporter.js b/packages/jest-jasmine2/src/reporter.ts similarity index 81% rename from packages/jest-jasmine2/src/reporter.js rename to packages/jest-jasmine2/src/reporter.ts index 88557489cff2..657113da1976 100644 --- a/packages/jest-jasmine2/src/reporter.js +++ b/packages/jest-jasmine2/src/reporter.ts @@ -3,51 +3,44 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {GlobalConfig, Path, ProjectConfig} from 'types/Config'; -import type { - AssertionResult, - FailedAssertion, - Milliseconds, - Status, - TestResult, -} from 'types/TestResult'; - +import {Config, TestResult} from '@jest/types'; import {formatResultsErrors} from 'jest-message-util'; type Suite = { - description: string, + description: string; }; type SpecResult = { - __callsite?: Object, - description: string, - duration?: Milliseconds, - failedExpectations: Array, - fullName: string, - id: string, - status: Status, + __callsite?: { + getColumnNumber: () => number; + getLineNumber: () => number; + }; + description: string; + duration?: TestResult.Milliseconds; + failedExpectations: Array; + fullName: string; + id: string; + status: TestResult.Status; }; type Microseconds = number; export default class Jasmine2Reporter { - _testResults: Array; - _globalConfig: GlobalConfig; - _config: ProjectConfig; + _testResults: Array; + _globalConfig: Config.GlobalConfig; + _config: Config.ProjectConfig; _currentSuites: Array; _resolve: any; - _resultsPromise: Promise; + _resultsPromise: Promise; _startTimes: Map; - _testPath: Path; + _testPath: Config.Path; constructor( - globalConfig: GlobalConfig, - config: ProjectConfig, - testPath: Path, + globalConfig: Config.GlobalConfig, + config: Config.ProjectConfig, + testPath: Config.Path, ) { this._globalConfig = globalConfig; this._config = config; @@ -126,11 +119,11 @@ export default class Jasmine2Reporter { this._resolve(testResult); } - getResults(): Promise { + getResults(): Promise { return this._resultsPromise; } - _addMissingMessageToStack(stack: string, message: ?string) { + _addMissingMessageToStack(stack: string, message: string | undefined) { // Some errors (e.g. Angular injection error) don't prepend error.message // to stack, instead the first line of the stack is just plain 'Error' const ERROR_REGEX = /^Error\s*\n/; @@ -148,7 +141,7 @@ export default class Jasmine2Reporter { _extractSpecResults( specResult: SpecResult, ancestorTitles: Array, - ): AssertionResult { + ): TestResult.AssertionResult { const start = this._startTimes.get(specResult.id); const duration = start ? Date.now() - start : undefined; const status = @@ -156,11 +149,10 @@ export default class Jasmine2Reporter { const location = specResult.__callsite ? { column: specResult.__callsite.getColumnNumber(), - // $FlowFixMe: https://github.com/facebook/flow/issues/5213 line: specResult.__callsite.getLineNumber(), } : null; - const results = { + const results: TestResult.AssertionResult = { ancestorTitles, duration, failureMessages: [], diff --git a/packages/jest-jasmine2/src/setup_jest_globals.js b/packages/jest-jasmine2/src/setup_jest_globals.ts similarity index 72% rename from packages/jest-jasmine2/src/setup_jest_globals.js rename to packages/jest-jasmine2/src/setup_jest_globals.ts index c6a3c52f2612..982dd31b01ff 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.js +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -3,12 +3,9 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ -import type {GlobalConfig, Path, ProjectConfig} from 'types/Config'; -import type {Plugin} from 'types/PrettyFormat'; +import {PrettyFormat, Config} from '@jest/types'; import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import { @@ -17,12 +14,12 @@ import { addSerializer, } from 'jest-snapshot'; -export type SetupOptions = {| - config: ProjectConfig, - globalConfig: GlobalConfig, - localRequire: (moduleName: string) => Plugin, - testPath: Path, -|}; +export type SetupOptions = { + config: Config.ProjectConfig; + globalConfig: Config.GlobalConfig; + localRequire: (moduleName: string) => PrettyFormat.Plugin; + testPath: Config.Path; +}; // Get suppressed errors form jest-matchers that weren't throw during // test execution and add them to the test result, potentially failing @@ -61,27 +58,23 @@ const addAssertionErrors = result => { const patchJasmine = () => { global.jasmine.Spec = (realSpec => { - const Spec = function Spec(attr) { - const resultCallback = attr.resultCallback; - attr.resultCallback = function(result) { - addSuppressedErrors(result); - addAssertionErrors(result); - resultCallback.call(attr, result); - }; - const onStart = attr.onStart; - attr.onStart = context => { - setState({currentTestName: context.getFullName()}); - onStart && onStart.call(attr, context); - }; - realSpec.call(this, attr); - }; - - Spec.prototype = realSpec.prototype; - for (const statics in realSpec) { - if (Object.prototype.hasOwnProperty.call(realSpec, statics)) { - Spec[statics] = realSpec[statics]; + class Spec extends realSpec { + constructor(attr) { + const resultCallback = attr.resultCallback; + attr.resultCallback = function(result) { + addSuppressedErrors(result); + addAssertionErrors(result); + resultCallback.call(attr, result); + }; + const onStart = attr.onStart; + attr.onStart = context => { + setState({currentTestName: context.getFullName()}); + onStart && onStart.call(attr, context); + }; + super(attr); } } + return Spec; })(global.jasmine.Spec); }; diff --git a/packages/jest-jasmine2/src/treeProcessor.js b/packages/jest-jasmine2/src/treeProcessor.ts similarity index 75% rename from packages/jest-jasmine2/src/treeProcessor.js rename to packages/jest-jasmine2/src/treeProcessor.ts index 27b381fa1d0c..c10e362e69de 100644 --- a/packages/jest-jasmine2/src/treeProcessor.js +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -3,27 +3,25 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @flow */ type Options = { - nodeComplete: (suite: TreeNode) => void, - nodeStart: (suite: TreeNode) => void, - queueRunnerFactory: any, - runnableIds: Array, - tree: TreeNode, + nodeComplete: (suite: TreeNode) => void; + nodeStart: (suite: TreeNode) => void; + queueRunnerFactory: any; + runnableIds: Array; + tree: TreeNode; }; type TreeNode = { - afterAllFns: Array, - beforeAllFns: Array, - disabled?: boolean, - execute: (onComplete: () => void, enabled: boolean) => void, - id: string, - onException: (error: Error) => void, - sharedUserContext: () => any, - children?: Array, + afterAllFns: Array; + beforeAllFns: Array; + disabled?: boolean; + execute: (onComplete: () => void, enabled: boolean) => void; + id: string; + onException: (error: Error) => void; + sharedUserContext: () => any; + children?: Array; }; export default function treeProcessor(options: Options) { @@ -35,7 +33,7 @@ export default function treeProcessor(options: Options) { tree, } = options; - function isEnabled(node, parentEnabled) { + function isEnabled(node: TreeNode, parentEnabled: boolean) { return parentEnabled || runnableIds.indexOf(node.id) !== -1; } @@ -56,7 +54,7 @@ export default function treeProcessor(options: Options) { return async function fn(done: (error?: any) => void = () => {}) { nodeStart(node); await queueRunnerFactory({ - onException: error => node.onException(error), + onException: (error: Error) => node.onException(error), queueableFns: wrapChildren(node, enabled), userContext: node.sharedUserContext(), }); @@ -65,7 +63,7 @@ export default function treeProcessor(options: Options) { }; } - function hasEnabledTest(node: TreeNode) { + function hasEnabledTest(node: TreeNode): boolean { if (node.children) { return node.children.some(hasEnabledTest); } diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts new file mode 100644 index 000000000000..795c5fc1c415 --- /dev/null +++ b/packages/jest-jasmine2/src/types.ts @@ -0,0 +1,39 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import expect from 'expect'; + +// TODO Add expect types to @jest/types or leave it here +// Borrowed from "expect" +// -------START------- +export type SyncExpectationResult = { + pass: boolean; + message: () => string; +}; + +export type AsyncExpectationResult = Promise; + +export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; + +export type RawMatcherFn = ( + expected: any, + actual: any, + options?: any, +) => ExpectationResult; +// -------END------- + +export type Jasmine = { + Spec: unknown; +} & typeof expect; + +declare global { + module NodeJS { + interface Global { + jasmine: Jasmine; + } + } +} From 239e2c7a4bbdbc4c41150961d643e25949e90f8b Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 24 Feb 2019 12:30:58 +0500 Subject: [PATCH 02/25] Migration to ts (part 2) --- packages/jest-jasmine2/src/PCancelable.ts | 26 +- .../{Suite.test.js => Suite.test.ts} | 4 +- ... => expectationResultFactory.test.ts.snap} | 0 ...ers.test.js.snap => matchers.test.ts.snap} | 0 ...st.js => expectationResultFactory.test.ts} | 2 - ...{hooksError.test.js => hooksError.test.ts} | 2 - ...tTestError.test.js => itTestError.test.ts} | 6 +- ...estAlias.test.js => itToTestAlias.test.ts} | 2 - .../{iterators.test.js => iterators.test.ts} | 13 +- .../{matchers.test.js => matchers.test.ts} | 2 - .../{pTimeout.test.js => pTimeout.test.ts} | 2 - ...ueueRunner.test.js => queueRunner.test.ts} | 4 +- .../{reporter.test.js => reporter.test.ts} | 6 +- .../{todoError.test.js => todoError.test.ts} | 4 +- packages/jest-jasmine2/src/each.ts | 1 + .../src/expectationResultFactory.ts | 8 +- .../jest-jasmine2/src/jasmine/CallTracker.ts | 100 +- packages/jest-jasmine2/src/jasmine/Env.ts | 946 +++++++++--------- .../src/jasmine/JsApiReporter.ts | 141 +-- .../src/jasmine/ReportDispatcher.ts | 66 +- packages/jest-jasmine2/src/jasmine/Spec.ts | 344 ++++--- .../jest-jasmine2/src/jasmine/SpyStrategy.ts | 109 +- packages/jest-jasmine2/src/jasmine/Suite.ts | 263 ++--- .../jest-jasmine2/src/jasmine/createSpy.ts | 2 +- .../jest-jasmine2/src/jasmine/spyRegistry.ts | 301 +++--- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 6 +- packages/jest-jasmine2/src/jestExpect.ts | 5 +- packages/jest-jasmine2/src/queueRunner.ts | 4 +- packages/jest-jasmine2/src/reporter.ts | 4 +- .../jest-jasmine2/src/setup_jest_globals.ts | 8 +- 30 files changed, 1262 insertions(+), 1119 deletions(-) rename packages/jest-jasmine2/src/__tests__/{Suite.test.js => Suite.test.ts} (95%) rename packages/jest-jasmine2/src/__tests__/__snapshots__/{expectationResultFactory.test.js.snap => expectationResultFactory.test.ts.snap} (100%) rename packages/jest-jasmine2/src/__tests__/__snapshots__/{matchers.test.js.snap => matchers.test.ts.snap} (100%) rename packages/jest-jasmine2/src/__tests__/{expectationResultFactory.test.js => expectationResultFactory.test.ts} (99%) rename packages/jest-jasmine2/src/__tests__/{hooksError.test.js => hooksError.test.ts} (98%) rename packages/jest-jasmine2/src/__tests__/{itTestError.test.js => itTestError.test.ts} (95%) rename packages/jest-jasmine2/src/__tests__/{itToTestAlias.test.js => itToTestAlias.test.ts} (94%) rename packages/jest-jasmine2/src/__tests__/{iterators.test.js => iterators.test.ts} (88%) rename packages/jest-jasmine2/src/__tests__/{matchers.test.js => matchers.test.ts} (96%) rename packages/jest-jasmine2/src/__tests__/{pTimeout.test.js => pTimeout.test.ts} (99%) rename packages/jest-jasmine2/src/__tests__/{queueRunner.test.js => queueRunner.test.ts} (98%) rename packages/jest-jasmine2/src/__tests__/{reporter.test.js => reporter.test.ts} (93%) rename packages/jest-jasmine2/src/__tests__/{todoError.test.js => todoError.test.ts} (95%) diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index 9a6e9eb37451..e4cd7f931e66 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -12,7 +12,15 @@ class CancelError extends Error { } } -class PCancelable { +class PCancelable extends Promise { + private _pending: boolean; + private _canceled: boolean; + private _cancel?: () => unknown; + private _reject: (reason?: any) => unknown; + private _promise: Promise; + + static CancelError: CancelError; + static fn(fn) { return function() { const args = [].slice.apply(arguments); @@ -23,7 +31,8 @@ class PCancelable { }; } - constructor(executor) { + // @ts-ignore + constructor(executor: (onCancel, resolve, reject) => any) { this._pending = true; this._canceled = false; @@ -46,12 +55,12 @@ class PCancelable { }); } - then() { - return this._promise.then.apply(this._promise, arguments); + then(...args: unknown[]) { + return this._promise.then.apply(this._promise, args); } - catch() { - return this._promise.catch.apply(this._promise, arguments); + catch(...args: unknown[]) { + return this._promise.catch.apply(this._promise, args); } cancel() { @@ -76,7 +85,4 @@ class PCancelable { } } -Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); - -module.exports = PCancelable; -module.exports.CancelError = CancelError; +export = PCancelable; diff --git a/packages/jest-jasmine2/src/__tests__/Suite.test.js b/packages/jest-jasmine2/src/__tests__/Suite.test.ts similarity index 95% rename from packages/jest-jasmine2/src/__tests__/Suite.test.js rename to packages/jest-jasmine2/src/__tests__/Suite.test.ts index 6850a9351496..1c4350454901 100644 --- a/packages/jest-jasmine2/src/__tests__/Suite.test.js +++ b/packages/jest-jasmine2/src/__tests__/Suite.test.ts @@ -6,12 +6,10 @@ * */ -'use strict'; - import Suite from '../jasmine/Suite'; describe('Suite', () => { - let suite; + let suite: Suite; beforeEach(() => { suite = new Suite({ diff --git a/packages/jest-jasmine2/src/__tests__/__snapshots__/expectationResultFactory.test.js.snap b/packages/jest-jasmine2/src/__tests__/__snapshots__/expectationResultFactory.test.ts.snap similarity index 100% rename from packages/jest-jasmine2/src/__tests__/__snapshots__/expectationResultFactory.test.js.snap rename to packages/jest-jasmine2/src/__tests__/__snapshots__/expectationResultFactory.test.ts.snap diff --git a/packages/jest-jasmine2/src/__tests__/__snapshots__/matchers.test.js.snap b/packages/jest-jasmine2/src/__tests__/__snapshots__/matchers.test.ts.snap similarity index 100% rename from packages/jest-jasmine2/src/__tests__/__snapshots__/matchers.test.js.snap rename to packages/jest-jasmine2/src/__tests__/__snapshots__/matchers.test.ts.snap diff --git a/packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.js b/packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.ts similarity index 99% rename from packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.js rename to packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.ts index af70b5f3b952..fdf940eab04c 100644 --- a/packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.js +++ b/packages/jest-jasmine2/src/__tests__/expectationResultFactory.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - import expectationResultFactory from '../expectationResultFactory'; describe('expectationResultFactory', () => { diff --git a/packages/jest-jasmine2/src/__tests__/hooksError.test.js b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts similarity index 98% rename from packages/jest-jasmine2/src/__tests__/hooksError.test.js rename to packages/jest-jasmine2/src/__tests__/hooksError.test.ts index 6f6ca1e87f81..1de5568e261d 100644 --- a/packages/jest-jasmine2/src/__tests__/hooksError.test.js +++ b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -'use strict'; - describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( '%s hooks error throwing', fn => { diff --git a/packages/jest-jasmine2/src/__tests__/itTestError.test.js b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts similarity index 95% rename from packages/jest-jasmine2/src/__tests__/itTestError.test.js rename to packages/jest-jasmine2/src/__tests__/itTestError.test.ts index bcce79f21121..e230949e8f28 100644 --- a/packages/jest-jasmine2/src/__tests__/itTestError.test.js +++ b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - describe('test/it error throwing', () => { it(`it throws error with missing callback function`, () => { expect(() => { @@ -18,11 +16,13 @@ describe('test/it error throwing', () => { }); it(`it throws an error when first argument isn't a string`, () => { expect(() => { + // @ts-ignore it(() => {}); }).toThrowError(`Invalid first argument, () => {}. It must be a string.`); }); it('it throws an error when callback function is not a function', () => { expect(() => { + // @ts-ignore it('test3', 'test3b'); }).toThrowError( 'Invalid second argument, test3b. It must be a callback function.', @@ -37,11 +37,13 @@ describe('test/it error throwing', () => { }); test(`test throws an error when first argument isn't a string`, () => { expect(() => { + // @ts-ignore test(() => {}); }).toThrowError(`Invalid first argument, () => {}. It must be a string.`); }); test('test throws an error when callback function is not a function', () => { expect(() => { + // @ts-ignore test('test6', 'test6b'); }).toThrowError( 'Invalid second argument, test6b. It must be a callback function.', diff --git a/packages/jest-jasmine2/src/__tests__/itToTestAlias.test.js b/packages/jest-jasmine2/src/__tests__/itToTestAlias.test.ts similarity index 94% rename from packages/jest-jasmine2/src/__tests__/itToTestAlias.test.js rename to packages/jest-jasmine2/src/__tests__/itToTestAlias.test.ts index a2e55740c1ce..4d108b2b0b93 100644 --- a/packages/jest-jasmine2/src/__tests__/itToTestAlias.test.js +++ b/packages/jest-jasmine2/src/__tests__/itToTestAlias.test.ts @@ -6,6 +6,4 @@ * */ -'use strict'; - test('global.test', () => {}); diff --git a/packages/jest-jasmine2/src/__tests__/iterators.test.js b/packages/jest-jasmine2/src/__tests__/iterators.test.ts similarity index 88% rename from packages/jest-jasmine2/src/__tests__/iterators.test.js rename to packages/jest-jasmine2/src/__tests__/iterators.test.ts index c7d214bbff50..1c45192c41e6 100644 --- a/packages/jest-jasmine2/src/__tests__/iterators.test.js +++ b/packages/jest-jasmine2/src/__tests__/iterators.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - describe('iterators', () => { it('works for arrays', () => { const mixedArray = [1, {}, []]; @@ -55,9 +53,14 @@ describe('iterators', () => { }); it('works for Maps', () => { - const keyValuePairs = [['key1', 'value1'], ['key2', 'value2']]; - const smallerKeyValuePairs = [['key1', 'value1']]; - const biggerKeyValuePairs = [ + const keyValuePairs: ReadonlyArray<[string, string]> = [ + ['key1', 'value1'], + ['key2', 'value2'], + ]; + const smallerKeyValuePairs: ReadonlyArray<[string, string]> = [ + ['key1', 'value1'], + ]; + const biggerKeyValuePairs: ReadonlyArray<[string, string]> = [ ['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3'], diff --git a/packages/jest-jasmine2/src/__tests__/matchers.test.js b/packages/jest-jasmine2/src/__tests__/matchers.test.ts similarity index 96% rename from packages/jest-jasmine2/src/__tests__/matchers.test.js rename to packages/jest-jasmine2/src/__tests__/matchers.test.ts index 15a0c8a708cd..3dfb0b77aed4 100644 --- a/packages/jest-jasmine2/src/__tests__/matchers.test.js +++ b/packages/jest-jasmine2/src/__tests__/matchers.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - describe('matchers', () => { it('proxies matchers to expect', () => { expect(() => expect(1).toBe(2)).toThrowErrorMatchingSnapshot(); diff --git a/packages/jest-jasmine2/src/__tests__/pTimeout.test.js b/packages/jest-jasmine2/src/__tests__/pTimeout.test.ts similarity index 99% rename from packages/jest-jasmine2/src/__tests__/pTimeout.test.js rename to packages/jest-jasmine2/src/__tests__/pTimeout.test.ts index 84c8e7408a9a..fef80a2bd541 100644 --- a/packages/jest-jasmine2/src/__tests__/pTimeout.test.js +++ b/packages/jest-jasmine2/src/__tests__/pTimeout.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - jest.useFakeTimers(); import pTimeout from '../pTimeout'; diff --git a/packages/jest-jasmine2/src/__tests__/queueRunner.test.js b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts similarity index 98% rename from packages/jest-jasmine2/src/__tests__/queueRunner.test.js rename to packages/jest-jasmine2/src/__tests__/queueRunner.test.ts index 12f4dd6f719b..f76defe15fdf 100644 --- a/packages/jest-jasmine2/src/__tests__/queueRunner.test.js +++ b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts @@ -6,8 +6,6 @@ * */ -'use strict'; - import queueRunner from '../queueRunner'; describe('queueRunner', () => { @@ -87,7 +85,7 @@ describe('queueRunner', () => { }); it('passes an error to `onException` on timeout.', async () => { - const fnOne = jest.fn(next => {}); + const fnOne = jest.fn(_next => {}); const fnTwo = jest.fn(next => next()); const onException = jest.fn(); const options = { diff --git a/packages/jest-jasmine2/src/__tests__/reporter.test.js b/packages/jest-jasmine2/src/__tests__/reporter.test.ts similarity index 93% rename from packages/jest-jasmine2/src/__tests__/reporter.test.js rename to packages/jest-jasmine2/src/__tests__/reporter.test.ts index ee005c8fd743..aacdb9dca778 100644 --- a/packages/jest-jasmine2/src/__tests__/reporter.test.js +++ b/packages/jest-jasmine2/src/__tests__/reporter.test.ts @@ -6,19 +6,17 @@ * */ -'use strict'; - import JasmineReporter from '../reporter'; describe('Jasmine2Reporter', () => { - let reporter; + let reporter: JasmineReporter; beforeEach(() => { reporter = new JasmineReporter({}); }); it('reports nested suites', () => { - const makeSpec = name => ({ + const makeSpec = (name: string) => ({ description: 'description', failedExpectations: [], fullName: name, diff --git a/packages/jest-jasmine2/src/__tests__/todoError.test.js b/packages/jest-jasmine2/src/__tests__/todoError.test.ts similarity index 95% rename from packages/jest-jasmine2/src/__tests__/todoError.test.js rename to packages/jest-jasmine2/src/__tests__/todoError.test.ts index ffde32d86406..758cfda9140e 100644 --- a/packages/jest-jasmine2/src/__tests__/todoError.test.js +++ b/packages/jest-jasmine2/src/__tests__/todoError.test.ts @@ -6,11 +6,10 @@ * */ -'use strict'; - describe('test/it.todo error throwing', () => { it('it throws error when given no arguments', () => { expect(() => { + // @ts-ignore it.todo(); }).toThrowError('Todo must be called with only a description.'); }); @@ -21,6 +20,7 @@ describe('test/it.todo error throwing', () => { }); it('it throws error when given none string description', () => { expect(() => { + // @ts-ignore it.todo(() => {}); }).toThrowError('Todo must be called with only a description.'); }); diff --git a/packages/jest-jasmine2/src/each.ts b/packages/jest-jasmine2/src/each.ts index 22cde37e5166..33a54a831552 100644 --- a/packages/jest-jasmine2/src/each.ts +++ b/packages/jest-jasmine2/src/each.ts @@ -6,6 +6,7 @@ */ import {Environment} from '@jest/types'; +// @ts-ignore TODO Remove ignore when jest-each is migrated to TS import {bind as bindEach} from 'jest-each'; export default (environment: Environment.Environment): void => { diff --git a/packages/jest-jasmine2/src/expectationResultFactory.ts b/packages/jest-jasmine2/src/expectationResultFactory.ts index e4f7a3961a4a..e7c4e9ce97e7 100644 --- a/packages/jest-jasmine2/src/expectationResultFactory.ts +++ b/packages/jest-jasmine2/src/expectationResultFactory.ts @@ -7,7 +7,7 @@ import prettyFormat from 'pretty-format'; -function messageFormatter({error, message, passed}) { +function messageFormatter({error, message, passed}: Options) { if (passed) { return 'Passed.'; } @@ -29,7 +29,11 @@ function messageFormatter({error, message, passed}) { return `thrown: ${prettyFormat(error, {maxDepth: 3})}`; } -function stackFormatter(options, initError, errorMessage) { +function stackFormatter( + options: Options, + initError: Error | undefined, + errorMessage: string, +) { if (options.passed) { return ''; } diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.ts b/packages/jest-jasmine2/src/jasmine/CallTracker.ts index 9c8cf9a201c3..41570acbdc69 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.ts +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -29,50 +29,62 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -function CallTracker() { - let calls = []; - - this.track = function(context) { - calls.push(context); - }; - - this.any = function() { - return !!calls.length; - }; - - this.count = function() { - return calls.length; - }; - - this.argsFor = function(index) { - const call = calls[index]; - return call ? call.args : []; - }; - - this.all = function() { - return calls; - }; - - this.allArgs = function() { - const callArgs = []; - for (let i = 0; i < calls.length; i++) { - callArgs.push(calls[i].args); - } - - return callArgs; - }; - - this.first = function() { - return calls[0]; - }; - - this.mostRecent = function() { - return calls[calls.length - 1]; - }; - - this.reset = function() { - calls = []; - }; +class CallTracker { + track: (context: unknown) => void; + any: () => boolean; + count: () => number; + argsFor: (index: number) => unknown[]; + all: () => unknown[]; + allArgs: () => unknown[]; + first: () => unknown; + mostRecent: () => unknown; + reset: () => void; + + constructor() { + let calls = []; + + this.track = function(context) { + calls.push(context); + }; + + this.any = function() { + return !!calls.length; + }; + + this.count = function() { + return calls.length; + }; + + this.argsFor = function(index) { + const call = calls[index]; + return call ? call.args : []; + }; + + this.all = function() { + return calls; + }; + + this.allArgs = function() { + const callArgs = []; + for (let i = 0; i < calls.length; i++) { + callArgs.push(calls[i].args); + } + + return callArgs; + }; + + this.first = function() { + return calls[0]; + }; + + this.mostRecent = function() { + return calls[calls.length - 1]; + }; + + this.reset = function() { + calls = []; + }; + } } export default CallTracker; diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 49e8963980b7..7747bffd4e8a 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -38,563 +38,575 @@ import assertionErrorMessage from '../assertionErrorMessage'; import {ErrorWithStack} from 'jest-util'; export default function(j$) { - function Env(options) { - options = options || {}; + class Env { + specFilter: () => boolean; + catchExceptions: (value: unknown) => unknown; + throwOnExpectationFailure: (value: unknown) => void; + catchingExceptions: () => unknown; + topSuite: () => unknown; + fail: (error: unknown) => void; + pending: (message: unknown) => void; + afterAll: (afterAllFunction: unknown, timeout: unknown) => void; + fit: (description: unknown, fn: unknown, timeout: unknown) => unknown; + + constructor(options?: {}) { + options = options || {}; + + const self = this; + + let totalSpecsDefined = 0; + + let catchExceptions = true; + + const realSetTimeout = global.setTimeout; + const realClearTimeout = global.clearTimeout; + + const runnableResources = {}; + let currentSpec = null; + const currentlyExecutingSuites = []; + let currentDeclarationSuite = null; + let throwOnExpectationFailure = false; + let random = false; + let seed = null; + + const currentSuite = function() { + return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; + }; - const self = this; + const currentRunnable = function() { + return currentSpec || currentSuite(); + }; - let totalSpecsDefined = 0; + const reporter = new j$.ReportDispatcher([ + 'jasmineStarted', + 'jasmineDone', + 'suiteStarted', + 'suiteDone', + 'specStarted', + 'specDone', + ]); + + this.specFilter = function() { + return true; + }; - let catchExceptions = true; + let nextSpecId = 0; + const getNextSpecId = function() { + return 'spec' + nextSpecId++; + }; - const realSetTimeout = global.setTimeout; - const realClearTimeout = global.clearTimeout; + let nextSuiteId = 0; + const getNextSuiteId = function() { + return 'suite' + nextSuiteId++; + }; - const runnableResources = {}; - let currentSpec = null; - const currentlyExecutingSuites = []; - let currentDeclarationSuite = null; - let throwOnExpectationFailure = false; - let random = false; - let seed = null; + const defaultResourcesForRunnable = function(id, parentRunnableId) { + const resources = {spies: []}; - const currentSuite = function() { - return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; - }; + runnableResources[id] = resources; + }; - const currentRunnable = function() { - return currentSpec || currentSuite(); - }; + const clearResourcesForRunnable = function(id) { + spyRegistry.clearSpies(); + delete runnableResources[id]; + }; - const reporter = new j$.ReportDispatcher([ - 'jasmineStarted', - 'jasmineDone', - 'suiteStarted', - 'suiteDone', - 'specStarted', - 'specDone', - ]); + const beforeAndAfterFns = function(suite) { + return function() { + let afters = []; + let befores = []; - this.specFilter = function() { - return true; - }; + while (suite) { + befores = befores.concat(suite.beforeFns); + afters = afters.concat(suite.afterFns); - let nextSpecId = 0; - const getNextSpecId = function() { - return 'spec' + nextSpecId++; - }; + suite = suite.parentSuite; + } - let nextSuiteId = 0; - const getNextSuiteId = function() { - return 'suite' + nextSuiteId++; - }; + return { + befores: befores.reverse(), + afters, + }; + }; + }; - const defaultResourcesForRunnable = function(id, parentRunnableId) { - const resources = {spies: []}; + const getSpecName = function(spec, suite) { + const fullName = [spec.description]; + const suiteFullName = suite.getFullName(); - runnableResources[id] = resources; - }; + if (suiteFullName !== '') { + fullName.unshift(suiteFullName); + } - const clearResourcesForRunnable = function(id) { - spyRegistry.clearSpies(); - delete runnableResources[id]; - }; + return fullName.join(' '); + }; - const beforeAndAfterFns = function(suite) { - return function() { - let afters = []; - let befores = []; + this.catchExceptions = function(value) { + catchExceptions = !!value; + return catchExceptions; + }; - while (suite) { - befores = befores.concat(suite.beforeFns); - afters = afters.concat(suite.afterFns); + this.catchingExceptions = function() { + return catchExceptions; + }; - suite = suite.parentSuite; - } + this.throwOnExpectationFailure = function(value) { + throwOnExpectationFailure = !!value; + }; - return { - befores: befores.reverse(), - afters, - }; + this.throwingExpectationFailures = function() { + return throwOnExpectationFailure; }; - }; - const getSpecName = function(spec, suite) { - const fullName = [spec.description]; - const suiteFullName = suite.getFullName(); + this.randomizeTests = function(value) { + random = !!value; + }; - if (suiteFullName !== '') { - fullName.unshift(suiteFullName); - } + this.randomTests = function() { + return random; + }; - return fullName.join(' '); - }; + this.seed = function(value) { + if (value) { + seed = value; + } + return seed; + }; - this.catchExceptions = function(value) { - catchExceptions = !!value; - return catchExceptions; - }; + function queueRunnerFactory(options) { + options.clearTimeout = realClearTimeout; + options.fail = self.fail; + options.setTimeout = realSetTimeout; + return queueRunner(options); + } - this.catchingExceptions = function() { - return catchExceptions; - }; + const topSuite = new j$.Suite({ + id: getNextSuiteId(), + getTestPath() { + return j$.testPath; + }, + }); - this.throwOnExpectationFailure = function(value) { - throwOnExpectationFailure = !!value; - }; + currentDeclarationSuite = topSuite; - this.throwingExpectationFailures = function() { - return throwOnExpectationFailure; - }; + this.topSuite = function() { + return topSuite; + }; - this.randomizeTests = function(value) { - random = !!value; - }; + const uncaught = err => { + if (currentSpec) { + currentSpec.onException(err); + currentSpec.cancel(); + } else { + console.error('Unhandled error'); + console.error(err.stack); + } + }; - this.randomTests = function() { - return random; - }; + let oldListenersException; + let oldListenersRejection; + const executionSetup = function() { + // Need to ensure we are the only ones handling these exceptions. + oldListenersException = process.listeners('uncaughtException').slice(); + oldListenersRejection = process.listeners('unhandledRejection').slice(); - this.seed = function(value) { - if (value) { - seed = value; - } - return seed; - }; - - function queueRunnerFactory(options) { - options.clearTimeout = realClearTimeout; - options.fail = self.fail; - options.setTimeout = realSetTimeout; - return queueRunner(options); - } + j$.process.removeAllListeners('uncaughtException'); + j$.process.removeAllListeners('unhandledRejection'); - const topSuite = new j$.Suite({ - id: getNextSuiteId(), - getTestPath() { - return j$.testPath; - }, - }); - - currentDeclarationSuite = topSuite; - - this.topSuite = function() { - return topSuite; - }; - - const uncaught = err => { - if (currentSpec) { - currentSpec.onException(err); - currentSpec.cancel(); - } else { - console.error('Unhandled error'); - console.error(err.stack); - } - }; + j$.process.on('uncaughtException', uncaught); + j$.process.on('unhandledRejection', uncaught); + }; - let oldListenersException; - let oldListenersRejection; - const executionSetup = function() { - // Need to ensure we are the only ones handling these exceptions. - oldListenersException = process.listeners('uncaughtException').slice(); - oldListenersRejection = process.listeners('unhandledRejection').slice(); + const executionTeardown = function() { + j$.process.removeListener('uncaughtException', uncaught); + j$.process.removeListener('unhandledRejection', uncaught); - j$.process.removeAllListeners('uncaughtException'); - j$.process.removeAllListeners('unhandledRejection'); + // restore previous exception handlers + oldListenersException.forEach(listener => { + j$.process.on('uncaughtException', listener); + }); - j$.process.on('uncaughtException', uncaught); - j$.process.on('unhandledRejection', uncaught); - }; + oldListenersRejection.forEach(listener => { + j$.process.on('unhandledRejection', listener); + }); + }; - const executionTeardown = function() { - j$.process.removeListener('uncaughtException', uncaught); - j$.process.removeListener('unhandledRejection', uncaught); + this.execute = async function(runnablesToRun, suiteTree = topSuite) { + if (!runnablesToRun) { + if (focusedRunnables.length) { + runnablesToRun = focusedRunnables; + } else { + runnablesToRun = [suiteTree.id]; + } + } - // restore previous exception handlers - oldListenersException.forEach(listener => { - j$.process.on('uncaughtException', listener); - }); + if (currentlyExecutingSuites.length === 0) { + executionSetup(); + } - oldListenersRejection.forEach(listener => { - j$.process.on('unhandledRejection', listener); - }); - }; + const lastDeclarationSuite = currentDeclarationSuite; + + await treeProcessor({ + nodeComplete(suite) { + if (!suite.disabled) { + clearResourcesForRunnable(suite.id); + } + currentlyExecutingSuites.pop(); + if (suite === topSuite) { + reporter.jasmineDone({ + failedExpectations: topSuite.result.failedExpectations, + }); + } else { + reporter.suiteDone(suite.getResult()); + } + }, + nodeStart(suite) { + currentlyExecutingSuites.push(suite); + defaultResourcesForRunnable( + suite.id, + suite.parentSuite && suite.parentSuite.id, + ); + if (suite === topSuite) { + reporter.jasmineStarted({totalSpecsDefined}); + } else { + reporter.suiteStarted(suite.result); + } + }, + queueRunnerFactory, + runnableIds: runnablesToRun, + tree: suiteTree, + }); - this.execute = async function(runnablesToRun, suiteTree = topSuite) { - if (!runnablesToRun) { - if (focusedRunnables.length) { - runnablesToRun = focusedRunnables; - } else { - runnablesToRun = [suiteTree.id]; + currentDeclarationSuite = lastDeclarationSuite; + + if (currentlyExecutingSuites.length === 0) { + executionTeardown(); } - } + }; - if (currentlyExecutingSuites.length === 0) { - executionSetup(); - } + this.addReporter = function(reporterToAdd) { + reporter.addReporter(reporterToAdd); + }; - const lastDeclarationSuite = currentDeclarationSuite; + this.provideFallbackReporter = function(reporterToAdd) { + reporter.provideFallbackReporter(reporterToAdd); + }; - await treeProcessor({ - nodeComplete(suite) { - if (!suite.disabled) { - clearResourcesForRunnable(suite.id); - } - currentlyExecutingSuites.pop(); - if (suite === topSuite) { - reporter.jasmineDone({ - failedExpectations: topSuite.result.failedExpectations, - }); - } else { - reporter.suiteDone(suite.getResult()); - } - }, - nodeStart(suite) { - currentlyExecutingSuites.push(suite); - defaultResourcesForRunnable( - suite.id, - suite.parentSuite && suite.parentSuite.id, - ); - if (suite === topSuite) { - reporter.jasmineStarted({totalSpecsDefined}); - } else { - reporter.suiteStarted(suite.result); + this.clearReporters = function() { + reporter.clearReporters(); + }; + + const spyRegistry = new j$.SpyRegistry({ + currentSpies() { + if (!currentRunnable()) { + throw new Error( + 'Spies must be created in a before function or a spec', + ); } + return runnableResources[currentRunnable().id].spies; }, - queueRunnerFactory, - runnableIds: runnablesToRun, - tree: suiteTree, }); - currentDeclarationSuite = lastDeclarationSuite; - - if (currentlyExecutingSuites.length === 0) { - executionTeardown(); - } - }; + this.allowRespy = function(allow) { + spyRegistry.allowRespy(allow); + }; - this.addReporter = function(reporterToAdd) { - reporter.addReporter(reporterToAdd); - }; + this.spyOn = function() { + return spyRegistry.spyOn.apply(spyRegistry, arguments); + }; - this.provideFallbackReporter = function(reporterToAdd) { - reporter.provideFallbackReporter(reporterToAdd); - }; + const suiteFactory = function(description) { + const suite = new j$.Suite({ + id: getNextSuiteId(), + description, + parentSuite: currentDeclarationSuite, + throwOnExpectationFailure, + getTestPath() { + return j$.testPath; + }, + }); - this.clearReporters = function() { - reporter.clearReporters(); - }; + return suite; + }; - const spyRegistry = new j$.SpyRegistry({ - currentSpies() { - if (!currentRunnable()) { + this.describe = function(description, specDefinitions) { + const suite = suiteFactory(description); + if (specDefinitions === undefined) { + throw new Error( + `Missing second argument. It must be a callback function.`, + ); + } + if (typeof specDefinitions !== 'function') { throw new Error( - 'Spies must be created in a before function or a spec', + `Invalid second argument, ${specDefinitions}. It must be a callback function.`, ); } - return runnableResources[currentRunnable().id].spies; - }, - }); + if (specDefinitions.length > 0) { + throw new Error('describe does not expect any arguments'); + } + if (currentDeclarationSuite.markedPending) { + suite.pend(); + } + if (currentDeclarationSuite.markedTodo) { + suite.todo(); + } + addSpecsToSuite(suite, specDefinitions); + return suite; + }; - this.allowRespy = function(allow) { - spyRegistry.allowRespy(allow); - }; + this.xdescribe = function(description, specDefinitions) { + const suite = suiteFactory(description); + suite.pend(); + addSpecsToSuite(suite, specDefinitions); + return suite; + }; - this.spyOn = function() { - return spyRegistry.spyOn.apply(spyRegistry, arguments); - }; + const focusedRunnables = []; - const suiteFactory = function(description) { - const suite = new j$.Suite({ - id: getNextSuiteId(), - description, - parentSuite: currentDeclarationSuite, - throwOnExpectationFailure, - getTestPath() { - return j$.testPath; - }, - }); + this.fdescribe = function(description, specDefinitions) { + const suite = suiteFactory(description); + suite.isFocused = true; - return suite; - }; + focusedRunnables.push(suite.id); + unfocusAncestor(); + addSpecsToSuite(suite, specDefinitions); - this.describe = function(description, specDefinitions) { - const suite = suiteFactory(description); - if (specDefinitions === undefined) { - throw new Error( - `Missing second argument. It must be a callback function.`, - ); - } - if (typeof specDefinitions !== 'function') { - throw new Error( - `Invalid second argument, ${specDefinitions}. It must be a callback function.`, - ); - } - if (specDefinitions.length > 0) { - throw new Error('describe does not expect any arguments'); - } - if (currentDeclarationSuite.markedPending) { - suite.pend(); - } - if (currentDeclarationSuite.markedTodo) { - suite.todo(); - } - addSpecsToSuite(suite, specDefinitions); - return suite; - }; - - this.xdescribe = function(description, specDefinitions) { - const suite = suiteFactory(description); - suite.pend(); - addSpecsToSuite(suite, specDefinitions); - return suite; - }; - - const focusedRunnables = []; - - this.fdescribe = function(description, specDefinitions) { - const suite = suiteFactory(description); - suite.isFocused = true; - - focusedRunnables.push(suite.id); - unfocusAncestor(); - addSpecsToSuite(suite, specDefinitions); - - return suite; - }; - - function addSpecsToSuite(suite, specDefinitions) { - const parentSuite = currentDeclarationSuite; - parentSuite.addChild(suite); - currentDeclarationSuite = suite; - - let declarationError = null; - try { - specDefinitions.call(suite); - } catch (e) { - declarationError = e; - } + return suite; + }; - if (declarationError) { - self.it('encountered a declaration exception', () => { - throw declarationError; - }); - } + function addSpecsToSuite(suite, specDefinitions) { + const parentSuite = currentDeclarationSuite; + parentSuite.addChild(suite); + currentDeclarationSuite = suite; - currentDeclarationSuite = parentSuite; - } + let declarationError = null; + try { + specDefinitions.call(suite); + } catch (e) { + declarationError = e; + } - function findFocusedAncestor(suite) { - while (suite) { - if (suite.isFocused) { - return suite.id; + if (declarationError) { + self.it('encountered a declaration exception', () => { + throw declarationError; + }); } - suite = suite.parentSuite; + + currentDeclarationSuite = parentSuite; } - return null; - } + function findFocusedAncestor(suite) { + while (suite) { + if (suite.isFocused) { + return suite.id; + } + suite = suite.parentSuite; + } + + return null; + } - function unfocusAncestor() { - const focusedAncestor = findFocusedAncestor(currentDeclarationSuite); - if (focusedAncestor) { - for (let i = 0; i < focusedRunnables.length; i++) { - if (focusedRunnables[i] === focusedAncestor) { - focusedRunnables.splice(i, 1); - break; + function unfocusAncestor() { + const focusedAncestor = findFocusedAncestor(currentDeclarationSuite); + if (focusedAncestor) { + for (let i = 0; i < focusedRunnables.length; i++) { + if (focusedRunnables[i] === focusedAncestor) { + focusedRunnables.splice(i, 1); + break; + } } } } - } - const specFactory = function(description, fn, suite, timeout) { - totalSpecsDefined++; - const spec = new j$.Spec({ - id: getNextSpecId(), - beforeAndAfterFns: beforeAndAfterFns(suite), - resultCallback: specResultCallback, - getSpecName(spec) { - return getSpecName(spec, suite); - }, - getTestPath() { - return j$.testPath; - }, - onStart: specStarted, - description, - queueRunnerFactory, - userContext() { - return suite.clonedSharedUserContext(); - }, - queueableFn: { - fn, - timeout() { - return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + const specFactory = function(description, fn, suite, timeout) { + totalSpecsDefined++; + const spec = new j$.Spec({ + id: getNextSpecId(), + beforeAndAfterFns: beforeAndAfterFns(suite), + resultCallback: specResultCallback, + getSpecName(spec) { + return getSpecName(spec, suite); }, - }, - throwOnExpectationFailure, - }); + getTestPath() { + return j$.testPath; + }, + onStart: specStarted, + description, + queueRunnerFactory, + userContext() { + return suite.clonedSharedUserContext(); + }, + queueableFn: { + fn, + timeout() { + return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + }, + }, + throwOnExpectationFailure, + }); - if (!self.specFilter(spec)) { - spec.disable(); - } + if (!self.specFilter(spec)) { + spec.disable(); + } - return spec; + return spec; - function specResultCallback(result) { - clearResourcesForRunnable(spec.id); - currentSpec = null; - reporter.specDone(result); - } + function specResultCallback(result) { + clearResourcesForRunnable(spec.id); + currentSpec = null; + reporter.specDone(result); + } - function specStarted(spec) { - currentSpec = spec; - defaultResourcesForRunnable(spec.id, suite.id); - reporter.specStarted(spec.result); - } - }; + function specStarted(spec) { + currentSpec = spec; + defaultResourcesForRunnable(spec.id, suite.id); + reporter.specStarted(spec.result); + } + }; - this.it = function(description, fn, timeout) { - if (typeof description !== 'string') { - throw new Error( - `Invalid first argument, ${description}. It must be a string.`, - ); - } - if (fn === undefined) { - throw new Error( - 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', - ); - } - if (typeof fn !== 'function') { - throw new Error( - `Invalid second argument, ${fn}. It must be a callback function.`, + this.it = function(description, fn, timeout) { + if (typeof description !== 'string') { + throw new Error( + `Invalid first argument, ${description}. It must be a string.`, + ); + } + if (fn === undefined) { + throw new Error( + 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', + ); + } + if (typeof fn !== 'function') { + throw new Error( + `Invalid second argument, ${fn}. It must be a callback function.`, + ); + } + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout, ); - } - const spec = specFactory( - description, - fn, - currentDeclarationSuite, - timeout, - ); - if (currentDeclarationSuite.markedPending) { - spec.pend(); - } + if (currentDeclarationSuite.markedPending) { + spec.pend(); + } - // When a test is defined inside another, jasmine will not run it. - // This check throws an error to warn the user about the edge-case. - if (currentSpec !== null) { - throw new Error( - 'Tests cannot be nested. Test `' + + // When a test is defined inside another, jasmine will not run it. + // This check throws an error to warn the user about the edge-case. + if (currentSpec !== null) { + throw new Error( + 'Tests cannot be nested. Test `' + spec.description + '` cannot run because it is nested within `' + currentSpec.description + '`.', + ); + } + currentDeclarationSuite.addChild(spec); + return spec; + }; + + this.xit = function() { + const spec = this.it.apply(this, arguments); + spec.pend('Temporarily disabled with xit'); + return spec; + }; + + this.todo = function() { + const description = arguments[0]; + if (arguments.length !== 1 || typeof description !== 'string') { + throw new ErrorWithStack( + 'Todo must be called with only a description.', + test.todo, + ); + } + + const spec = specFactory(description, () => {}, currentDeclarationSuite); + spec.todo(); + currentDeclarationSuite.addChild(spec); + return spec; + }; + + this.fit = function(description, fn, timeout) { + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout, ); - } - currentDeclarationSuite.addChild(spec); - return spec; - }; - - this.xit = function() { - const spec = this.it.apply(this, arguments); - spec.pend('Temporarily disabled with xit'); - return spec; - }; - - this.todo = function() { - const description = arguments[0]; - if (arguments.length !== 1 || typeof description !== 'string') { - throw new ErrorWithStack( - 'Todo must be called with only a description.', - test.todo, - ); - } + currentDeclarationSuite.addChild(spec); + focusedRunnables.push(spec.id); + unfocusAncestor(); + return spec; + }; - const spec = specFactory(description, () => {}, currentDeclarationSuite); - spec.todo(); - currentDeclarationSuite.addChild(spec); - return spec; - }; - - this.fit = function(description, fn, timeout) { - const spec = specFactory( - description, - fn, - currentDeclarationSuite, - timeout, - ); - currentDeclarationSuite.addChild(spec); - focusedRunnables.push(spec.id); - unfocusAncestor(); - return spec; - }; - - this.beforeEach = function(beforeEachFunction, timeout) { - currentDeclarationSuite.beforeEach({ - fn: beforeEachFunction, - timeout() { - return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; - }, - }); - }; + this.beforeEach = function(beforeEachFunction, timeout) { + currentDeclarationSuite.beforeEach({ + fn: beforeEachFunction, + timeout() { + return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + }, + }); + }; - this.beforeAll = function(beforeAllFunction, timeout) { - currentDeclarationSuite.beforeAll({ - fn: beforeAllFunction, - timeout() { - return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; - }, - }); - }; + this.beforeAll = function(beforeAllFunction, timeout) { + currentDeclarationSuite.beforeAll({ + fn: beforeAllFunction, + timeout() { + return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + }, + }); + }; - this.afterEach = function(afterEachFunction, timeout) { - currentDeclarationSuite.afterEach({ - fn: afterEachFunction, - timeout() { - return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; - }, - }); - }; + this.afterEach = function(afterEachFunction, timeout) { + currentDeclarationSuite.afterEach({ + fn: afterEachFunction, + timeout() { + return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + }, + }); + }; - this.afterAll = function(afterAllFunction, timeout) { - currentDeclarationSuite.afterAll({ - fn: afterAllFunction, - timeout() { - return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; - }, - }); - }; + this.afterAll = function(afterAllFunction, timeout) { + currentDeclarationSuite.afterAll({ + fn: afterAllFunction, + timeout() { + return timeout || j$._DEFAULT_TIMEOUT_INTERVAL; + }, + }); + }; - this.pending = function(message) { - let fullMessage = j$.Spec.pendingSpecExceptionMessage; - if (message) { - fullMessage += message; - } - throw fullMessage; - }; + this.pending = function(message) { + let fullMessage = j$.Spec.pendingSpecExceptionMessage; + if (message) { + fullMessage += message; + } + throw fullMessage; + }; - this.fail = function(error) { - let checkIsError; - let message; + this.fail = function(error) { + let checkIsError; + let message; - if (error instanceof AssertionError) { - checkIsError = false; - message = assertionErrorMessage(error, {expand: j$.Spec.expand}); - } else { - const check = isError(error); + if (error instanceof AssertionError) { + checkIsError = false; + message = assertionErrorMessage(error, {expand: j$.Spec.expand}); + } else { + const check = isError(error); - checkIsError = check.isError; - message = check.message; - } + checkIsError = check.isError; + message = check.message; + } - currentRunnable().addExpectationResult(false, { - matcherName: '', - passed: false, - expected: '', - actual: '', - message, - error: checkIsError ? error : new Error(message), - }); - }; + currentRunnable().addExpectationResult(false, { + matcherName: '', + passed: false, + expected: '', + actual: '', + message, + error: checkIsError ? error : new Error(message), + }); + }; + } } return Env; diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index e3dc646a8022..82f50d99ec99 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -37,79 +37,98 @@ const noopTimer = { }, }; -export default function JsApiReporter(options: Object) { - const timer = options.timer || noopTimer; - let status = 'loaded'; - - this.started = false; - this.finished = false; - this.runDetails = {}; - - this.jasmineStarted = function() { - this.started = true; - status = 'started'; - timer.start(); - }; - - let executionTime; - - function validateAfterAllExceptions({failedExpectations}) { - if (failedExpectations && failedExpectations.length > 0) { - throw failedExpectations[0]; +export default class JsApiReporter { + started: boolean; + finished: boolean; + runDetails: unknown; + jasmineStarted: () => void; + jasmineDone: (runDetails: unknown) => void; + status: () => unknown; + executionTime: () => unknown; + + suiteStarted: (result: unknown) => void; + suiteDone: (result: unknown) => void; + suiteResults: (index: number, length: number) => unknown[]; + suites: () => unknown; + + specResults: (index: number, length: number) => unknown[]; + specDone: (result: unknown) => void; + specs: () => unknown; + + constructor(options: {timer?: unknown}) { + const timer = options.timer || noopTimer; + let status = 'loaded'; + + this.started = false; + this.finished = false; + this.runDetails = {}; + + this.jasmineStarted = () => { + this.started = true; + status = 'started'; + timer.start(); + }; + + let executionTime; + + function validateAfterAllExceptions({failedExpectations}) { + if (failedExpectations && failedExpectations.length > 0) { + throw failedExpectations[0]; + } } - } - this.jasmineDone = function(runDetails) { - validateAfterAllExceptions(runDetails); - this.finished = true; - this.runDetails = runDetails; - executionTime = timer.elapsed(); - status = 'done'; - }; + this.jasmineDone = function(runDetails) { + validateAfterAllExceptions(runDetails); + this.finished = true; + this.runDetails = runDetails; + executionTime = timer.elapsed(); + status = 'done'; + }; - this.status = function() { - return status; - }; + this.status = function() { + return status; + }; - const suites = []; - const suites_hash = {}; + const suites = []; + const suites_hash = {}; - this.suiteStarted = function(result) { - suites_hash[result.id] = result; - }; + this.suiteStarted = function(result) { + suites_hash[result.id] = result; + }; - this.suiteDone = function(result) { - storeSuite(result); - }; + this.suiteDone = function(result) { + storeSuite(result); + }; - this.suiteResults = function(index, length) { - return suites.slice(index, index + length); - }; + this.suiteResults = function(index, length) { + return suites.slice(index, index + length); + }; - function storeSuite(result) { - suites.push(result); - suites_hash[result.id] = result; - } + function storeSuite(result) { + suites.push(result); + suites_hash[result.id] = result; + } - this.suites = function() { - return suites_hash; - }; + this.suites = function() { + return suites_hash; + }; - const specs = []; + const specs = []; - this.specDone = function(result) { - specs.push(result); - }; + this.specDone = function(result) { + specs.push(result); + }; - this.specResults = function(index, length) { - return specs.slice(index, index + length); - }; + this.specResults = function(index, length) { + return specs.slice(index, index + length); + }; - this.specs = function() { - return specs; - }; + this.specs = function() { + return specs; + }; - this.executionTime = function() { - return executionTime; - }; + this.executionTime = function() { + return executionTime; + }; + } } diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index d34b565f8de2..d77cf2d31ae3 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -29,43 +29,49 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -export default function ReportDispatcher(methods: Array) { - const dispatchedMethods = methods || []; +export default class ReportDispatcher { + addReporter: (reporter: unknown) => void; + provideFallbackReporter: (reporter: unknown) => void; + clearReporters: () => void; - for (let i = 0; i < dispatchedMethods.length; i++) { - const method = dispatchedMethods[i]; - this[method] = (function(m) { - return function() { - dispatch(m, arguments); - }; - })(method); - } + constructor(methods: Array) { + const dispatchedMethods = methods || []; - let reporters = []; - let fallbackReporter = null; + for (let i = 0; i < dispatchedMethods.length; i++) { + const method = dispatchedMethods[i]; + this[method] = (function(m) { + return function() { + dispatch(m, arguments); + }; + })(method); + } - this.addReporter = function(reporter) { - reporters.push(reporter); - }; + let reporters = []; + let fallbackReporter = null; - this.provideFallbackReporter = function(reporter) { - fallbackReporter = reporter; - }; + this.addReporter = function(reporter) { + reporters.push(reporter); + }; - this.clearReporters = function() { - reporters = []; - }; + this.provideFallbackReporter = function(reporter) { + fallbackReporter = reporter; + }; - return this; + this.clearReporters = function() { + reporters = []; + }; - function dispatch(method, args) { - if (reporters.length === 0 && fallbackReporter !== null) { - reporters.push(fallbackReporter); - } - for (let i = 0; i < reporters.length; i++) { - const reporter = reporters[i]; - if (reporter[method]) { - reporter[method].apply(reporter, args); + return this; + + function dispatch(method: string, args) { + if (reporters.length === 0 && fallbackReporter !== null) { + reporters.push(fallbackReporter); + } + for (let i = 0; i < reporters.length; i++) { + const reporter = reporters[i]; + if (reporter[method]) { + reporter[method].apply(reporter, args); + } } } } diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index b4fb2d8bb6e2..fb645fae2224 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -38,183 +38,233 @@ import expectationResultFactory from '../expectationResultFactory'; import assertionErrorMessage from '../assertionErrorMessage'; -export default function Spec(attrs: Object) { - this.resultCallback = attrs.resultCallback || function() {}; - this.id = attrs.id; - this.description = attrs.description || ''; - this.queueableFn = attrs.queueableFn; - this.beforeAndAfterFns = - attrs.beforeAndAfterFns || - function() { - return {befores: [], afters: []}; - }; - this.userContext = - attrs.userContext || - function() { - return {}; - }; - this.onStart = attrs.onStart || function() {}; - this.getSpecName = - attrs.getSpecName || - function() { - return ''; - }; - this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; - this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; - - this.initError = new Error(); - this.initError.name = ''; - - // Without this line v8 stores references to all closures - // in the stack in the Error object. This line stringifies the stack - // property to allow garbage-collecting objects on the stack - // https://crbug.com/v8/7142 - this.initError.stack = this.initError.stack; - - this.queueableFn.initError = this.initError; - - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [], - passedExpectations: [], - pendingReason: '', - testPath: attrs.getTestPath(), +export default class Spec { + id: unknown; + description: string; + resultCallback: () => unknown; + queueableFn: unknown; + beforeAndAfterFns: () => {befores: unknown[]; afters: unknown[]}; + userContext: () => unknown; + onStart: () => unknown; + getSpecName: (spec: Spec) => string; + queueRunnerFactory: () => unknown; + throwOnExpectationFailure: boolean; + initError: Error; + result: { + id: unknown; + description: unknown; + fullName: string; + failedExpectations: []; + testPath: unknown; + passedExpectations: unknown[]; + pendingReason: string; }; -} + disabled: boolean; + currentRun: unknown; + markedTodo: boolean; + markedPending: boolean; + expand: boolean; + + static pendingSpecExceptionMessage = '=> marked Pending'; + + static isPendingSpecException(e: unknown) { + return !!( + e && + e.toString && + e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 + ); + } -Spec.prototype.addExpectationResult = function(passed, data, isError) { - const expectationResult = expectationResultFactory(data, this.initError); - if (passed) { - this.result.passedExpectations.push(expectationResult); - } else { - this.result.failedExpectations.push(expectationResult); + constructor(attrs: { + id: unknown; + resultCallback: () => unknown; + description: string; + throwOnExpectationFailure: unknown; + getTestPath: () => unknown; + queueableFn: unknown; + beforeAndAfterFns: unknown; + userContext: unknown; + onStart: unknown; + getSpecName: () => string; + queueRunnerFactory: () => unknown; + }) { + this.resultCallback = attrs.resultCallback || function() {}; + this.id = attrs.id; + this.description = attrs.description || ''; + this.queueableFn = attrs.queueableFn; + this.beforeAndAfterFns = + attrs.beforeAndAfterFns || + function() { + return {befores: [], afters: []}; + }; + this.userContext = + attrs.userContext || + function() { + return {}; + }; + this.onStart = attrs.onStart || function() {}; + this.getSpecName = + attrs.getSpecName || + function() { + return ''; + }; + this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + + this.initError = new Error(); + this.initError.name = ''; + + // Without this line v8 stores references to all closures + // in the stack in the Error object. This line stringifies the stack + // property to allow garbage-collecting objects on the stack + // https://crbug.com/v8/7142 + this.initError.stack = this.initError.stack; + + this.queueableFn.initError = this.initError; + + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [], + pendingReason: '', + testPath: attrs.getTestPath(), + }; + } + + addExpectationResult(passed, data, isError) { + const expectationResult = expectationResultFactory(data, this.initError); + if (passed) { + this.result.passedExpectations.push(expectationResult); + } else { + this.result.failedExpectations.push(expectationResult); - if (this.throwOnExpectationFailure && !isError) { - throw new ExpectationFailed(); + if (this.throwOnExpectationFailure && !isError) { + throw new ExpectationFailed(); + } } } -}; -Spec.prototype.execute = function(onComplete, enabled) { - const self = this; + execute(onComplete, enabled) { + const self = this; - this.onStart(this); + this.onStart(this); - if ( - !this.isExecutable() || - this.markedPending || - this.markedTodo || - enabled === false - ) { - complete(enabled); - return; - } + if ( + !this.isExecutable() || + this.markedPending || + this.markedTodo || + enabled === false + ) { + complete(enabled); + return; + } - const fns = this.beforeAndAfterFns(); - const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); + const fns = this.beforeAndAfterFns(); + const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); - this.currentRun = this.queueRunnerFactory({ - queueableFns: allFns, - onException() { - self.onException.apply(self, arguments); - }, - userContext: this.userContext(), - }); + this.currentRun = this.queueRunnerFactory({ + queueableFns: allFns, + onException() { + self.onException.apply(self, arguments); + }, + userContext: this.userContext(), + }); - this.currentRun.then(() => complete(true)); + this.currentRun.then(() => complete(true)); - function complete(enabledAgain) { - self.result.status = self.status(enabledAgain); - self.resultCallback(self.result); + function complete(enabledAgain) { + self.result.status = self.status(enabledAgain); + self.resultCallback(self.result); - if (onComplete) { - onComplete(); + if (onComplete) { + onComplete(); + } } } -}; -Spec.prototype.cancel = function cancel() { - if (this.currentRun) { - this.currentRun.cancel(); + cancelcancel() { + if (this.currentRun) { + this.currentRun.cancel(); + } } -}; -Spec.prototype.onException = function onException(error) { - if (Spec.isPendingSpecException(error)) { - this.pend(extractCustomPendingMessage(error)); - return; - } + onExceptiononException(error) { + if (Spec.isPendingSpecException(error)) { + this.pend(extractCustomPendingMessage(error)); + return; + } - if (error instanceof ExpectationFailed) { - return; + if (error instanceof ExpectationFailed) { + return; + } + + if (error instanceof AssertionError) { + error = assertionErrorMessage(error, {expand: this.expand}); + } + + this.addExpectationResult( + false, + { + matcherName: '', + passed: false, + expected: '', + actual: '', + error, + }, + true, + ); } - if (error instanceof AssertionError) { - error = assertionErrorMessage(error, {expand: this.expand}); + disable() { + this.disabled = true; } - this.addExpectationResult( - false, - { - matcherName: '', - passed: false, - expected: '', - actual: '', - error, - }, - true, - ); -}; + pend(message) { + this.markedPending = true; + if (message) { + this.result.pendingReason = message; + } + } -Spec.prototype.disable = function() { - this.disabled = true; -}; + todo() { + this.markedTodo = true; + } -Spec.prototype.pend = function(message) { - this.markedPending = true; - if (message) { - this.result.pendingReason = message; + getResult() { + this.result.status = this.status(); + return this.result; } -}; -Spec.prototype.todo = function() { - this.markedTodo = true; -}; + status(enabled: boolean) { + if (this.disabled || enabled === false) { + return 'disabled'; + } -Spec.prototype.getResult = function() { - this.result.status = this.status(); - return this.result; -}; + if (this.markedTodo) { + return 'todo'; + } -Spec.prototype.status = function(enabled) { - if (this.disabled || enabled === false) { - return 'disabled'; - } + if (this.markedPending) { + return 'pending'; + } - if (this.markedTodo) { - return 'todo'; + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'passed'; + } } - if (this.markedPending) { - return 'pending'; + isExecutable() { + return !this.disabled; } - if (this.result.failedExpectations.length > 0) { - return 'failed'; - } else { - return 'passed'; + getFullName() { + return this.getSpecName(this); } -}; - -Spec.prototype.isExecutable = function() { - return !this.disabled; -}; - -Spec.prototype.getFullName = function() { - return this.getSpecName(this); -}; +} const extractCustomPendingMessage = function(e) { const fullMessage = e.toString(); @@ -226,13 +276,3 @@ const extractCustomPendingMessage = function(e) { return fullMessage.substr(boilerplateEnd); }; - -Spec.pendingSpecExceptionMessage = '=> marked Pending'; - -Spec.isPendingSpecException = function(e) { - return !!( - e && - e.toString && - e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 - ); -}; diff --git a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts index 2a996f085248..372d66cf5168 100644 --- a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts +++ b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts @@ -28,64 +28,79 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* @flow */ -export default function SpyStrategy(options: Object) { - options = options || {}; +export default class SpyStrategy { + identity: () => string; + exec: () => unknown; + callThrough: () => unknown; + returnValue: (value: unknown) => unknown; + returnValues: () => unknown; + throwError: (something: unknown) => unknown; + callFake: (fn: unknown) => unknown; + stub: (fn: unknown) => unknown; - const identity = options.name || 'unknown'; - const originalFn = options.fn || function() {}; - const getSpy = options.getSpy || function() {}; - let plan = function() {}; + constructor(options?: { + name: string; + fn: () => unknown; + getSpy: () => unknown; + }) { + options = options || {}; - this.identity = function() { - return identity; - }; + const identity = options.name || 'unknown'; + const originalFn = options.fn || function() {}; + const getSpy = options.getSpy || function() {}; + let plan = function() {}; - this.exec = function() { - return plan.apply(this, arguments); - }; + this.identity = function() { + return identity; + }; + + this.exec = function() { + return plan.apply(this, arguments); + }; - this.callThrough = function() { - plan = originalFn; - return getSpy(); - }; + this.callThrough = function() { + plan = originalFn; + return getSpy(); + }; - this.returnValue = function(value) { - plan = function() { - return value; + this.returnValue = function(value) { + plan = function() { + return value; + }; + return getSpy(); }; - return getSpy(); - }; - this.returnValues = function() { - const values = Array.prototype.slice.call(arguments); - plan = function() { - return values.shift(); + this.returnValues = function() { + const values = Array.prototype.slice.call(arguments); + plan = function() { + return values.shift(); + }; + return getSpy(); }; - return getSpy(); - }; - this.throwError = function(something) { - const error = something instanceof Error ? something : new Error(something); - plan = function() { - throw error; + this.throwError = function(something) { + const error = + something instanceof Error ? something : new Error(something); + plan = function() { + throw error; + }; + return getSpy(); }; - return getSpy(); - }; - this.callFake = function(fn) { - if (typeof fn !== 'function') { - throw new Error( - 'Argument passed to callFake should be a function, got ' + fn, - ); - } - plan = fn; - return getSpy(); - }; + this.callFake = function(fn) { + if (typeof fn !== 'function') { + throw new Error( + 'Argument passed to callFake should be a function, got ' + fn, + ); + } + plan = fn; + return getSpy(); + }; - this.stub = function(fn) { - plan = function() {}; - return getSpy(); - }; + this.stub = function(fn) { + plan = function() {}; + return getSpy(); + }; + } } diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index f8f2432903ae..5f02ac90676a 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -34,152 +34,173 @@ import {convertDescriptorToString} from 'jest-util'; import ExpectationFailed from '../ExpectationFailed'; import expectationResultFactory from '../expectationResultFactory'; -export default function Suite(attrs: Object) { - this.id = attrs.id; - this.parentSuite = attrs.parentSuite; - this.description = convertDescriptorToString(attrs.description); - this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; - - this.beforeFns = []; - this.afterFns = []; - this.beforeAllFns = []; - this.afterAllFns = []; - this.disabled = false; - - this.children = []; - - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [], - testPath: attrs.getTestPath(), +export default class Suite { + id: unknown; + parentSuite: unknown; + description: unknown; + throwOnExpectationFailure: unknown; + beforeFns: unknown; + afterFns: unknown; + beforeAllFns: unknown; + afterAllFns: unknown; + disabled: boolean; + children: unknown; + result: { + id: unknown; + description: unknown; + fullName: string; + failedExpectations: []; + testPath: unknown; }; -} - -Suite.prototype.getFullName = function() { - const fullName = []; - for ( - let parentSuite = this; - parentSuite; - parentSuite = parentSuite.parentSuite - ) { - if (parentSuite.parentSuite) { - fullName.unshift(parentSuite.description); + markedPending: boolean; + sharedContext: unknown; + + constructor(attrs: { + id: unknown; + parentSuite: unknown; + description: unknown; + throwOnExpectationFailure: unknown; + getTestPath: () => unknown; + }) { + this.id = attrs.id; + this.parentSuite = attrs.parentSuite; + this.description = convertDescriptorToString(attrs.description); + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + + this.beforeFns = []; + this.afterFns = []; + this.beforeAllFns = []; + this.afterAllFns = []; + this.disabled = false; + + this.children = []; + + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + testPath: attrs.getTestPath(), + }; + } + getFullName() { + const fullName = []; + for ( + let parentSuite = this; + parentSuite; + parentSuite = parentSuite.parentSuite + ) { + if (parentSuite.parentSuite) { + fullName.unshift(parentSuite.description); + } } + return fullName.join(' '); + } + disable() { + this.disabled = true; + } + pend(message) { + this.markedPending = true; + } + beforeEach(fn) { + this.beforeFns.unshift(fn); + } + beforeAll(fn) { + this.beforeAllFns.push(fn); + } + afterEach(fn) { + this.afterFns.unshift(fn); + } + afterAll(fn) { + this.afterAllFns.unshift(fn); } - return fullName.join(' '); -}; - -Suite.prototype.disable = function() { - this.disabled = true; -}; - -Suite.prototype.pend = function(message) { - this.markedPending = true; -}; - -Suite.prototype.beforeEach = function(fn) { - this.beforeFns.unshift(fn); -}; - -Suite.prototype.beforeAll = function(fn) { - this.beforeAllFns.push(fn); -}; -Suite.prototype.afterEach = function(fn) { - this.afterFns.unshift(fn); -}; + addChild(child) { + this.children.push(child); + } -Suite.prototype.afterAll = function(fn) { - this.afterAllFns.unshift(fn); -}; + status() { + if (this.disabled) { + return 'disabled'; + } -Suite.prototype.addChild = function(child) { - this.children.push(child); -}; + if (this.markedPending) { + return 'pending'; + } -Suite.prototype.status = function() { - if (this.disabled) { - return 'disabled'; + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'finished'; + } } - if (this.markedPending) { - return 'pending'; + isExecutable() { + return !this.disabled; } - if (this.result.failedExpectations.length > 0) { - return 'failed'; - } else { - return 'finished'; + canBeReentered() { + return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; } -}; - -Suite.prototype.isExecutable = function() { - return !this.disabled; -}; -Suite.prototype.canBeReentered = function() { - return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; -}; - -Suite.prototype.getResult = function() { - this.result.status = this.status(); - return this.result; -}; - -Suite.prototype.sharedUserContext = function() { - if (!this.sharedContext) { - this.sharedContext = {}; + getResult() { + this.result.status = this.status(); + return this.result; } - return this.sharedContext; -}; + sharedUserContext() { + if (!this.sharedContext) { + this.sharedContext = {}; + } -Suite.prototype.clonedSharedUserContext = function() { - return this.sharedUserContext(); -}; + return this.sharedContext; + } -Suite.prototype.onException = function() { - if (arguments[0] instanceof ExpectationFailed) { - return; + clonedSharedUserContext() { + return this.sharedUserContext(); } - if (isAfterAll(this.children)) { - const data = { - matcherName: '', - passed: false, - expected: '', - actual: '', - error: arguments[0], - }; - this.result.failedExpectations.push(expectationResultFactory(data)); - } else { - for (let i = 0; i < this.children.length; i++) { - const child = this.children[i]; - child.onException.apply(child, arguments); + onException() { + if (arguments[0] instanceof ExpectationFailed) { + return; } - } -}; -Suite.prototype.addExpectationResult = function() { - if (isAfterAll(this.children) && isFailure(arguments)) { - const data = arguments[1]; - this.result.failedExpectations.push(expectationResultFactory(data)); - if (this.throwOnExpectationFailure) { - throw new ExpectationFailed(); + if (isAfterAll(this.children)) { + const data = { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: arguments[0], + }; + this.result.failedExpectations.push(expectationResultFactory(data)); + } else { + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + child.onException.apply(child, arguments); + } } - } else { - for (let i = 0; i < this.children.length; i++) { - const child = this.children[i]; - try { - child.addExpectationResult.apply(child, arguments); - } catch (e) { - // keep going + } + + addExpectationResult() { + if (isAfterAll(this.children) && isFailure(arguments)) { + const data = arguments[1]; + this.result.failedExpectations.push(expectationResultFactory(data)); + if (this.throwOnExpectationFailure) { + throw new ExpectationFailed(); + } + } else { + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + try { + child.addExpectationResult.apply(child, arguments); + } catch (e) { + // keep going + } } } } -}; +} function isAfterAll(children) { return children && children[0] && children[0].result.status; diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index ba1a3485171c..e09ba23cf485 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -34,7 +34,7 @@ import CallTracker from './CallTracker'; import SpyStrategy from './SpyStrategy'; -function createSpy(name, originalFn) { +function createSpy(name: unknown, originalFn: unknown) { const spyStrategy = new SpyStrategy({ name, fn: originalFn, diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts index cbd32354733a..8e533f9af53c 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -36,7 +36,7 @@ import SpyStrategy from './SpyStrategy'; const formatErrorMsg = (domain: string, usage?: string) => { const usageDefinition = usage ? '\nUsage: ' + usage : ''; - return msg => domain + ' : ' + msg + usageDefinition; + return (msg: string) => domain + ' : ' + msg + usageDefinition; }; function isSpy(putativeSpy) { @@ -51,166 +51,183 @@ function isSpy(putativeSpy) { const getErrorMsg = formatErrorMsg('', 'spyOn(, )'); -export default function SpyRegistry(options: Object) { - options = options || {}; - const currentSpies = - options.currentSpies || - function() { - return []; +export default class SpyRegistry { + allowRespy: (allow: unknown) => void; + spyOn: (obj: unknown, methodName: string, accessType?: string) => unknown; + clearSpies: () => void; + respy: unknown; + + private _spyOnProperty: ( + obj: unknown, + propertyName: string, + accessType: string, + ) => unknown; + + constructor(options?: {currentSpies: () => unknown[]}) { + options = options || {}; + const currentSpies = + options.currentSpies || + function() { + return []; + }; + + this.allowRespy = function(allow) { + this.respy = allow; }; - this.allowRespy = function(allow) { - this.respy = allow; - }; - - this.spyOn = function(obj, methodName, accessType?: string) { - if (accessType) { - return this._spyOnProperty(obj, methodName, accessType); - } - - if (obj === void 0) { - throw new Error( - getErrorMsg( - 'could not find an object to spy upon for ' + methodName + '()', - ), - ); - } - - if (methodName === void 0) { - throw new Error(getErrorMsg('No method name supplied')); - } - - if (obj[methodName] === void 0) { - throw new Error(getErrorMsg(methodName + '() method does not exist')); - } - - if (obj[methodName] && isSpy(obj[methodName])) { - if (this.respy) { - return obj[methodName]; - } else { + this.spyOn = function(obj, methodName, accessType?: string) { + if (accessType) { + return this._spyOnProperty(obj, methodName, accessType); + } + + if (obj === void 0) { throw new Error( - getErrorMsg(methodName + ' has already been spied upon'), + getErrorMsg( + 'could not find an object to spy upon for ' + methodName + '()', + ), ); } - } - let descriptor; - try { - descriptor = Object.getOwnPropertyDescriptor(obj, methodName); - } catch (e) { - // IE 8 doesn't support `definePropery` on non-DOM nodes - } + if (methodName === void 0) { + throw new Error(getErrorMsg('No method name supplied')); + } - if (descriptor && !(descriptor.writable || descriptor.set)) { - throw new Error( - getErrorMsg(methodName + ' is not declared writable or has no setter'), - ); - } + if (obj[methodName] === void 0) { + throw new Error(getErrorMsg(methodName + '() method does not exist')); + } - const originalMethod = obj[methodName]; - const spiedMethod = createSpy(methodName, originalMethod); - let restoreStrategy; + if (obj[methodName] && isSpy(obj[methodName])) { + if (this.respy) { + return obj[methodName]; + } else { + throw new Error( + getErrorMsg(methodName + ' has already been spied upon'), + ); + } + } - if (Object.prototype.hasOwnProperty.call(obj, methodName)) { - restoreStrategy = function() { - obj[methodName] = originalMethod; - }; - } else { - restoreStrategy = function() { - if (!delete obj[methodName]) { + let descriptor; + try { + descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + } catch (e) { + // IE 8 doesn't support `definePropery` on non-DOM nodes + } + + if (descriptor && !(descriptor.writable || descriptor.set)) { + throw new Error( + getErrorMsg( + methodName + ' is not declared writable or has no setter', + ), + ); + } + + const originalMethod = obj[methodName]; + const spiedMethod = createSpy(methodName, originalMethod); + let restoreStrategy; + + if (Object.prototype.hasOwnProperty.call(obj, methodName)) { + restoreStrategy = function() { obj[methodName] = originalMethod; - } - }; - } - - currentSpies().push({ - restoreObjectToOriginalState: restoreStrategy, - }); - - obj[methodName] = spiedMethod; - - return spiedMethod; - }; - - this._spyOnProperty = function(obj, propertyName, accessType = 'get') { - if (!obj) { - throw new Error( - getErrorMsg('could not find an object to spy upon for ' + propertyName), - ); - } - - if (!propertyName) { - throw new Error(getErrorMsg('No property name supplied')); - } - - let descriptor; - try { - descriptor = Object.getOwnPropertyDescriptor(obj, propertyName); - } catch (e) { - // IE 8 doesn't support `definePropery` on non-DOM nodes - } - - if (!descriptor) { - throw new Error(getErrorMsg(propertyName + ' property does not exist')); - } - - if (!descriptor.configurable) { - throw new Error( - getErrorMsg(propertyName + ' is not declared configurable'), - ); - } - - if (!descriptor[accessType]) { - throw new Error( - getErrorMsg( - 'Property ' + - propertyName + - ' does not have access type ' + - accessType, - ), - ); - } - - if (obj[propertyName] && isSpy(obj[propertyName])) { - if (this.respy) { - return obj[propertyName]; + }; } else { + restoreStrategy = function() { + if (!delete obj[methodName]) { + obj[methodName] = originalMethod; + } + }; + } + + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy, + }); + + obj[methodName] = spiedMethod; + + return spiedMethod; + }; + + this._spyOnProperty = function(obj, propertyName, accessType = 'get') { + if (!obj) { throw new Error( - getErrorMsg(propertyName + ' has already been spied upon'), + getErrorMsg( + 'could not find an object to spy upon for ' + propertyName, + ), ); } - } - const originalDescriptor = descriptor; - const spiedProperty = createSpy(propertyName, descriptor[accessType]); - let restoreStrategy; + if (!propertyName) { + throw new Error(getErrorMsg('No property name supplied')); + } - if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { - restoreStrategy = function() { - Object.defineProperty(obj, propertyName, originalDescriptor); - }; - } else { - restoreStrategy = function() { - delete obj[propertyName]; - }; - } + let descriptor: PropertyDescriptor | undefined; + try { + descriptor = Object.getOwnPropertyDescriptor(obj, propertyName); + } catch (e) { + // IE 8 doesn't support `definePropery` on non-DOM nodes + } - currentSpies().push({ - restoreObjectToOriginalState: restoreStrategy, - }); + if (!descriptor) { + throw new Error(getErrorMsg(propertyName + ' property does not exist')); + } - const spiedDescriptor = {...descriptor, [accessType]: spiedProperty}; + if (!descriptor.configurable) { + throw new Error( + getErrorMsg(propertyName + ' is not declared configurable'), + ); + } - Object.defineProperty(obj, propertyName, spiedDescriptor); + if (!descriptor[accessType]) { + throw new Error( + getErrorMsg( + 'Property ' + + propertyName + + ' does not have access type ' + + accessType, + ), + ); + } - return spiedProperty; - }; + if (obj[propertyName] && isSpy(obj[propertyName])) { + if (this.respy) { + return obj[propertyName]; + } else { + throw new Error( + getErrorMsg(propertyName + ' has already been spied upon'), + ); + } + } - this.clearSpies = function() { - const spies = currentSpies(); - for (let i = spies.length - 1; i >= 0; i--) { - const spyEntry = spies[i]; - spyEntry.restoreObjectToOriginalState(); - } - }; + const originalDescriptor = descriptor; + const spiedProperty = createSpy(propertyName, descriptor[accessType]); + let restoreStrategy; + + if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { + restoreStrategy = function() { + Object.defineProperty(obj, propertyName, originalDescriptor); + }; + } else { + restoreStrategy = function() { + delete obj[propertyName]; + }; + } + + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy, + }); + + const spiedDescriptor = {...descriptor, [accessType]: spiedProperty}; + + Object.defineProperty(obj, propertyName, spiedDescriptor); + + return spiedProperty; + }; + + this.clearSpies = function() { + const spies = currentSpies(); + for (let i = spies.length - 1; i >= 0; i--) { + const spyEntry = spies[i]; + spyEntry.restoreObjectToOriginalState(); + } + }; + } } diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 9478ff1901a1..a45d8a6ff9a5 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -21,7 +21,7 @@ function isPromise(obj: any) { } function promisifyLifeCycleFunction(originalFn, env) { - return function(fn, timeout) { + return function(fn: Promise | GeneratorFunction, timeout: number) { if (!fn) { return originalFn.call(env); } @@ -123,13 +123,13 @@ function promisifyIt(originalFn, env, jasmine) { }; } -function makeConcurrent(originalFn: Function, env, mutex) { +function makeConcurrent(originalFn: Function, env, mutex: ReturnType) { return function(specName, fn, timeout) { if (env != null && !env.specFilter({getFullName: () => specName || ''})) { return originalFn.call(env, specName, () => Promise.resolve(), timeout); } - let promise; + let promise: Promise; try { promise = mutex(() => { const promise = fn(); diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index 09062d6a3fbc..109489b4aa86 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -47,6 +47,7 @@ export default (config: {expand: boolean}) => { Object.keys(jasmineMatchersObject).forEach(name => { jestMatchersObject[name] = function( this: Matchers.MatcherState, + ...args: unknown[] ): RawMatcherFn { // use "expect.extend" if you need to use equality testers (via this.equal) const result = jasmineMatchersObject[name](null, null); @@ -54,8 +55,8 @@ export default (config: {expand: boolean}) => { const negativeCompare = result.negativeCompare || result.compare; return this.isNot - ? negativeCompare.apply(null, arguments) - : result.compare.apply(null, arguments); + ? negativeCompare.apply(null, args) + : result.compare.apply(null, args); }; }); diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index 10d91167ab79..f573d99aa891 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -37,8 +37,8 @@ export default function queueRunner(options: Options) { resolve(); }; - next.fail = function() { - options.fail.apply(null, arguments); + next.fail = function(...args: unknown[]) { + options.fail.apply(null, args); resolve(); }; try { diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 657113da1976..60057aad78f4 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -8,11 +8,11 @@ import {Config, TestResult} from '@jest/types'; import {formatResultsErrors} from 'jest-message-util'; -type Suite = { +export type Suite = { description: string; }; -type SpecResult = { +export type SpecResult = { __callsite?: { getColumnNumber: () => number; getLineNumber: () => number; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 982dd31b01ff..ebf8290e275c 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -6,13 +6,13 @@ */ import {PrettyFormat, Config} from '@jest/types'; - import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import { buildSnapshotResolver, SnapshotState, addSerializer, } from 'jest-snapshot'; +import {SpecResult} from './reporter'; export type SetupOptions = { config: Config.ProjectConfig; @@ -24,7 +24,7 @@ export type SetupOptions = { // Get suppressed errors form jest-matchers that weren't throw during // test execution and add them to the test result, potentially failing // a passing test. -const addSuppressedErrors = result => { +const addSuppressedErrors = (result: SpecResult) => { const {suppressedErrors} = getState(); setState({suppressedErrors: []}); if (suppressedErrors.length) { @@ -42,7 +42,7 @@ const addSuppressedErrors = result => { } }; -const addAssertionErrors = result => { +const addAssertionErrors = (result: SpecResult) => { const assertionErrors = extractExpectedAssertionsErrors(); if (assertionErrors.length) { const jasmineErrors = assertionErrors.map(({actual, error, expected}) => ({ @@ -61,7 +61,7 @@ const patchJasmine = () => { class Spec extends realSpec { constructor(attr) { const resultCallback = attr.resultCallback; - attr.resultCallback = function(result) { + attr.resultCallback = function(result: SpecResult) { addSuppressedErrors(result); addAssertionErrors(result); resultCallback.call(attr, result); From 09867ae221bb8e7ea23f7becb7a4bd84a57e2928 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 24 Feb 2019 12:43:27 +0500 Subject: [PATCH 03/25] Configure ts config --- packages/jest-jasmine2/package.json | 1 + packages/jest-jasmine2/tsconfig.json | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 packages/jest-jasmine2/tsconfig.json diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index 562d0d5397e5..d236bf838a47 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -10,6 +10,7 @@ "main": "build/index.js", "dependencies": { "@babel/traverse": "^7.1.0", + "@jest/types": "^24.1.0", "chalk": "^2.0.1", "co": "^4.6.0", "expect": "^24.1.0", diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json new file mode 100644 index 000000000000..5d4714756bba --- /dev/null +++ b/packages/jest-jasmine2/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig", + "compilerOptions": { + "rootDir": "src", + "outDir": "build" + }, + "references": [ + {"path": "../jest-types"}, + {"path": "../expect"}, + {"path": "../jest-matcher-utils"}, + {"path": "../jest-matcher-util"}, + {"path": "../jest-snapshot"}, + {"path": "../jest-util"}, + {"path": "../pretty-format"}, + {"path": "../jest-diff"} + ] +} From 0d4c0041eb9dcdb5d77cbd85d450f129ca40b4a5 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 24 Feb 2019 13:19:16 +0500 Subject: [PATCH 04/25] Migrating TS (part 3) --- packages/jest-jasmine2/src/PCancelable.ts | 2 ++ .../jest-jasmine2/src/jasmine/CallTracker.ts | 17 ++++++---- packages/jest-jasmine2/src/jasmine/Spec.ts | 31 ++++++++++--------- .../jest-jasmine2/src/jasmine/createSpy.ts | 9 ++++-- .../jest-jasmine2/src/jasmine/spyRegistry.ts | 12 ++++--- packages/jest-jasmine2/src/queueRunner.ts | 5 +-- .../jest-jasmine2/src/setup_jest_globals.ts | 5 +-- packages/jest-types/src/Global.ts | 2 +- 8 files changed, 51 insertions(+), 32 deletions(-) diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index e4cd7f931e66..e6a8e42dac0d 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +/* eslint-disable no-this-before-super, constructor-super */ + class CancelError extends Error { constructor() { super('Promise was canceled'); diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.ts b/packages/jest-jasmine2/src/jasmine/CallTracker.ts index 41570acbdc69..89f03129f1e2 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.ts +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -29,21 +29,26 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +type Context = { + object: this; + args: unknown[]; +}; + class CallTracker { - track: (context: unknown) => void; + track: (context: Context) => void; any: () => boolean; count: () => number; argsFor: (index: number) => unknown[]; - all: () => unknown[]; + all: () => Context[]; allArgs: () => unknown[]; - first: () => unknown; - mostRecent: () => unknown; + first: () => Context; + mostRecent: () => Context; reset: () => void; constructor() { - let calls = []; + let calls: Context[] = []; - this.track = function(context) { + this.track = function(context: Context) { calls.push(context); }; diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index fb645fae2224..8183c213943a 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -33,10 +33,23 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import {AssertionError} from 'assert'; import ExpectationFailed from '../ExpectationFailed'; - import expectationResultFactory from '../expectationResultFactory'; - import assertionErrorMessage from '../assertionErrorMessage'; +import {SpecResult} from '../reporter'; + +export type Attributes = { + id: unknown; + resultCallback: (result: SpecResult) => void; + description: string; + throwOnExpectationFailure: unknown; + getTestPath: () => unknown; + queueableFn: unknown; + beforeAndAfterFns: unknown; + userContext: unknown; + onStart: (context: Spec) => void; + getSpecName: () => string; + queueRunnerFactory: () => unknown; +}; export default class Spec { id: unknown; @@ -75,19 +88,7 @@ export default class Spec { ); } - constructor(attrs: { - id: unknown; - resultCallback: () => unknown; - description: string; - throwOnExpectationFailure: unknown; - getTestPath: () => unknown; - queueableFn: unknown; - beforeAndAfterFns: unknown; - userContext: unknown; - onStart: unknown; - getSpecName: () => string; - queueRunnerFactory: () => unknown; - }) { + constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function() {}; this.id = attrs.id; this.description = attrs.description || ''; diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index e09ba23cf485..e15452c57827 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -34,7 +34,12 @@ import CallTracker from './CallTracker'; import SpyStrategy from './SpyStrategy'; -function createSpy(name: unknown, originalFn: unknown) { +type Spy = { + and: SpyStrategy; + calls: SpyStrategy; +}; + +function createSpy(name: string, originalFn: unknown): Spy { const spyStrategy = new SpyStrategy({ name, fn: originalFn, @@ -43,7 +48,7 @@ function createSpy(name: unknown, originalFn: unknown) { }, }); const callTracker = new CallTracker(); - const spy = function() { + const spy = function(this: unknown) { const callData = { object: this, args: Array.prototype.slice.apply(arguments), diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts index 8e533f9af53c..a70941edfa83 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -53,14 +53,18 @@ const getErrorMsg = formatErrorMsg('', 'spyOn(, )'); export default class SpyRegistry { allowRespy: (allow: unknown) => void; - spyOn: (obj: unknown, methodName: string, accessType?: string) => unknown; + spyOn: ( + obj: {[key: string]: any}, + methodName: string, + accessType?: keyof PropertyDescriptor, + ) => unknown; clearSpies: () => void; respy: unknown; private _spyOnProperty: ( - obj: unknown, + obj: {[key: string]: any}, propertyName: string, - accessType: string, + accessType: keyof PropertyDescriptor, ) => unknown; constructor(options?: {currentSpies: () => unknown[]}) { @@ -75,7 +79,7 @@ export default class SpyRegistry { this.respy = allow; }; - this.spyOn = function(obj, methodName, accessType?: string) { + this.spyOn = (obj, methodName, accessType) => { if (accessType) { return this._spyOnProperty(obj, methodName, accessType); } diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index f573d99aa891..5a7f9304544a 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -30,9 +30,10 @@ export default function queueRunner(options: Options) { const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => { let promise = new Promise(resolve => { - const next = function(err) { + const next = function(...args: unknown[]) { + const err = args[0]; if (err) { - options.fail.apply(null, arguments); + options.fail.apply(null, args); } resolve(); }; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index ebf8290e275c..d977a78a10d1 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -13,6 +13,7 @@ import { addSerializer, } from 'jest-snapshot'; import {SpecResult} from './reporter'; +import JasmineSpec, {Attributes} from './jasmine/Spec'; export type SetupOptions = { config: Config.ProjectConfig; @@ -59,7 +60,7 @@ const addAssertionErrors = (result: SpecResult) => { const patchJasmine = () => { global.jasmine.Spec = (realSpec => { class Spec extends realSpec { - constructor(attr) { + constructor(attr: Attributes) { const resultCallback = attr.resultCallback; attr.resultCallback = function(result: SpecResult) { addSuppressedErrors(result); @@ -67,7 +68,7 @@ const patchJasmine = () => { resultCallback.call(attr, result); }; const onStart = attr.onStart; - attr.onStart = context => { + attr.onStart = (context: JasmineSpec) => { setState({currentTestName: context.getFullName()}); onStart && onStart.call(attr, context); }; diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index ed7739615e14..1a782eaaa386 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -48,7 +48,7 @@ export interface Describe extends DescribeBase { skip: ItBase; } -export interface Global { +export interface Global extends NodeJS.Global { it: It; test: ItConcurrent; fit: ItBase; From f57370a9a60a80bff397f65394b7e58a4e268d70 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 24 Feb 2019 10:45:01 +0100 Subject: [PATCH 05/25] fix typo --- packages/jest-jasmine2/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json index 5d4714756bba..ac1c17ec8821 100644 --- a/packages/jest-jasmine2/tsconfig.json +++ b/packages/jest-jasmine2/tsconfig.json @@ -8,7 +8,7 @@ {"path": "../jest-types"}, {"path": "../expect"}, {"path": "../jest-matcher-utils"}, - {"path": "../jest-matcher-util"}, + {"path": "../jest-message-util"}, {"path": "../jest-snapshot"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, From f9d102583c51e81c1501604b38cee57890eb1fff Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 24 Feb 2019 10:45:34 +0100 Subject: [PATCH 06/25] include types in package.json --- packages/jest-jasmine2/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index d236bf838a47..f555c88fb0d2 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -8,6 +8,7 @@ }, "license": "MIT", "main": "build/index.js", + "types": "build/index.d.ts", "dependencies": { "@babel/traverse": "^7.1.0", "@jest/types": "^24.1.0", From e2877b01a29c4f9ba84aa3db817ebe15a71fefb4 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 24 Feb 2019 18:16:48 +0500 Subject: [PATCH 07/25] Migrating TS (part 4) --- packages/jest-jasmine2/src/PCancelable.ts | 28 +-- .../src/expectationResultFactory.ts | 5 +- packages/jest-jasmine2/src/index.ts | 10 +- .../jest-jasmine2/src/jasmine/CallTracker.ts | 5 +- packages/jest-jasmine2/src/jasmine/Env.ts | 169 +++++++++++------- .../src/jasmine/JsApiReporter.ts | 37 ++-- .../src/jasmine/ReportDispatcher.ts | 7 +- packages/jest-jasmine2/src/jasmine/Spec.ts | 96 ++++++---- .../jest-jasmine2/src/jasmine/SpyStrategy.ts | 29 ++- packages/jest-jasmine2/src/jasmine/Suite.ts | 91 +++++----- packages/jest-jasmine2/src/jasmine/Timer.ts | 2 +- .../jest-jasmine2/src/jasmine/createSpy.ts | 18 +- .../jest-jasmine2/src/jasmine/jasmineLight.ts | 16 +- .../jest-jasmine2/src/jasmine/spyRegistry.ts | 15 +- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 30 ++-- packages/jest-jasmine2/src/queueRunner.ts | 21 ++- packages/jest-jasmine2/src/reporter.ts | 21 +-- .../jest-jasmine2/src/setup_jest_globals.ts | 6 +- packages/jest-jasmine2/src/treeProcessor.ts | 12 +- packages/jest-jasmine2/src/types.ts | 31 +++- packages/jest-types/src/TestResult.ts | 3 +- .../src/convertDescriptorToString.ts | 2 +- 22 files changed, 367 insertions(+), 287 deletions(-) diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index e6a8e42dac0d..0751e95a269f 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -14,19 +14,19 @@ class CancelError extends Error { } } -class PCancelable extends Promise { +// @ts-ignore +class PCancelable extends Promise { private _pending: boolean; private _canceled: boolean; - private _cancel?: () => unknown; - private _reject: (reason?: any) => unknown; - private _promise: Promise; + private _cancel?: Function; + private _reject: (reason?: any) => void; + private _promise: Promise; static CancelError: CancelError; - static fn(fn) { - return function() { - const args = [].slice.apply(arguments); - return new PCancelable((onCancel, resolve, reject) => { + static fn any>(fn: F) { + return function(...args: Parameters) { + return new PCancelable>((onCancel, resolve, reject) => { args.unshift(onCancel); fn.apply(null, args).then(resolve, reject); }); @@ -38,18 +38,18 @@ class PCancelable extends Promise { this._pending = true; this._canceled = false; - this._promise = new Promise((resolve, reject) => { + this._promise = new Promise((resolve, reject) => { this._reject = reject; return executor( - fn => { + (fn: Function) => { this._cancel = fn; }, - val => { + (val: unknown) => { this._pending = false; resolve(val); }, - err => { + (err?: any) => { this._pending = false; reject(err); }, @@ -57,11 +57,11 @@ class PCancelable extends Promise { }); } - then(...args: unknown[]) { + then(...args: Parameters['then']>) { return this._promise.then.apply(this._promise, args); } - catch(...args: unknown[]) { + catch(...args: Parameters['catch']>) { return this._promise.catch.apply(this._promise, args); } diff --git a/packages/jest-jasmine2/src/expectationResultFactory.ts b/packages/jest-jasmine2/src/expectationResultFactory.ts index e7c4e9ce97e7..52959c082256 100644 --- a/packages/jest-jasmine2/src/expectationResultFactory.ts +++ b/packages/jest-jasmine2/src/expectationResultFactory.ts @@ -6,6 +6,7 @@ */ import prettyFormat from 'pretty-format'; +import {TestResult} from '@jest/types'; function messageFormatter({error, message, passed}: Options) { if (passed) { @@ -55,7 +56,7 @@ function stackFormatter( return new Error(errorMessage).stack; } -type Options = { +export type Options = { matcherName: string; passed: boolean; actual?: any; @@ -67,7 +68,7 @@ type Options = { export default function expectationResultFactory( options: Options, initError?: Error, -) { +): TestResult.FailedAssertion { const message = messageFormatter(options); const stack = stackFormatter(options, initError, message); diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 3c6f1625eed3..fab7298b10f2 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -8,6 +8,7 @@ import path from 'path'; import {Environment, Config, TestResult} from '@jest/types'; import {SnapshotState} from 'jest-snapshot'; +// @ts-ignore TODO Remove ignore when jest-runtime is migrated to TS import Runtime from 'jest-runtime'; import {getCallsite} from 'jest-util'; @@ -15,8 +16,9 @@ import installEach from './each'; import {installErrorOnPrivate} from './errorOnPrivate'; import JasmineReporter from './reporter'; import jasmineAsyncInstall from './jasmineAsyncInstall'; +import Spec from './jasmine/Spec'; -const JASMINE = require.resolve('./jasmine/jasmineLight.js'); +const JASMINE = require.resolve('./jasmine/jasmineLight.ts'); async function jasmine2( globalConfig: Config.GlobalConfig, @@ -146,7 +148,7 @@ async function jasmine2( config.setupFilesAfterEnv.forEach(path => runtime.requireModule(path)); if (globalConfig.enabledTestsMap) { - env.specFilter = spec => { + env.specFilter = (spec: Spec) => { const suiteMap = globalConfig.enabledTestsMap && globalConfig.enabledTestsMap[spec.result.testPath]; @@ -154,7 +156,7 @@ async function jasmine2( }; } else if (globalConfig.testNamePattern) { const testNameRegex = new RegExp(globalConfig.testNamePattern, 'i'); - env.specFilter = spec => testNameRegex.test(spec.getFullName()); + env.specFilter = (spec: Spec) => testNameRegex.test(spec.getFullName()); } runtime.requireModule(testPath); @@ -198,4 +200,4 @@ const addSnapshotData = ( return results; }; -module.exports = jasmine2; +export = jasmine2; diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.ts b/packages/jest-jasmine2/src/jasmine/CallTracker.ts index 89f03129f1e2..2d680edbdedd 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.ts +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -29,9 +29,10 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -type Context = { - object: this; +export type Context = { + object: unknown; args: unknown[]; + returnValue?: unknown; }; class CallTracker { diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 7747bffd4e8a..01dfc79f39c4 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -31,29 +31,53 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable sort-keys */ import {AssertionError} from 'assert'; -import queueRunner from '../queueRunner'; +import {ErrorWithStack} from 'jest-util'; +import queueRunner, { + Options as QueueRunnerOptions, + QueueableFn, +} from '../queueRunner'; import treeProcessor from '../treeProcessor'; import isError from '../isError'; import assertionErrorMessage from '../assertionErrorMessage'; -import {ErrorWithStack} from 'jest-util'; +import {$J, Reporter} from '../types'; +import Spec, {SpecResult} from './Spec'; +import Suite from './Suite'; -export default function(j$) { +export default function(j$: $J) { class Env { - specFilter: () => boolean; - catchExceptions: (value: unknown) => unknown; + specFilter: (spec: Spec) => boolean; + catchExceptions: (value: unknown) => boolean; throwOnExpectationFailure: (value: unknown) => void; - catchingExceptions: () => unknown; - topSuite: () => unknown; - fail: (error: unknown) => void; - pending: (message: unknown) => void; - afterAll: (afterAllFunction: unknown, timeout: unknown) => void; - fit: (description: unknown, fn: unknown, timeout: unknown) => unknown; - - constructor(options?: {}) { - options = options || {}; - - const self = this; - + catchingExceptions: () => boolean; + topSuite: () => Suite; + fail: (error: Error | AssertionError) => void; + pending: (message: string) => void; + afterAll: (afterAllFunction: QueueableFn['fn'], timeout?: number) => void; + fit: (description: string, fn: QueueableFn['fn'], timeout?: number) => void; + throwingExpectationFailures: () => boolean; + randomizeTests: (value: unknown) => void; + randomTests: () => boolean; + seed: (value: unknown) => unknown; + execute: (runnablesToRun: string[], suiteTree?: Suite) => Promise; + fdescribe: (description: string, specDefinitions: Function) => Suite; + spyOn: () => any; + beforeEach: ( + beforeEachFunction: QueueableFn['fn'], + timeout?: number, + ) => void; + afterEach: (afterEachFunction: QueueableFn['fn'], timeout?: number) => void; + clearReporters: () => void; + addReporter: (reporterToAdd: Reporter) => void; + it: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec; + xdescribe: (description: string, specDefinitions: Function) => Suite; + xit: () => any; + beforeAll: (beforeAllFunction: Function, timeout?: number) => void; + todo: () => Spec; + provideFallbackReporter: (reporterToAdd: Reporter) => void; + allowRespy: (allow: boolean) => void; + describe: (description: string, specDefinitions: Function) => Suite; + + constructor(_options?: object) { let totalSpecsDefined = 0; let catchExceptions = true; @@ -61,13 +85,19 @@ export default function(j$) { const realSetTimeout = global.setTimeout; const realClearTimeout = global.clearTimeout; - const runnableResources = {}; - let currentSpec = null; - const currentlyExecutingSuites = []; - let currentDeclarationSuite = null; + const runnableResources: {[key: string]: {spies: []}} = {}; + const currentlyExecutingSuites: Suite[] = []; + let currentSpec: Spec | null = null; let throwOnExpectationFailure = false; let random = false; - let seed = null; + let seed: unknown | null = null; + const topSuite = new j$.Suite({ + id: getNextSuiteId(), + getTestPath() { + return j$.testPath; + }, + }); + let currentDeclarationSuite = topSuite; const currentSuite = function() { return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; @@ -96,31 +126,34 @@ export default function(j$) { }; let nextSuiteId = 0; - const getNextSuiteId = function() { + function getNextSuiteId() { return 'suite' + nextSuiteId++; - }; + } - const defaultResourcesForRunnable = function(id, parentRunnableId) { + const defaultResourcesForRunnable = function( + id: string, + _parentRunnableId?: string, + ) { const resources = {spies: []}; runnableResources[id] = resources; }; - const clearResourcesForRunnable = function(id) { + const clearResourcesForRunnable = function(id: string) { spyRegistry.clearSpies(); delete runnableResources[id]; }; - const beforeAndAfterFns = function(suite) { + const beforeAndAfterFns = function(suite: Suite) { return function() { - let afters = []; - let befores = []; + let afters: QueueableFn[] = []; + let befores: QueueableFn[] = []; while (suite) { befores = befores.concat(suite.beforeFns); afters = afters.concat(suite.afterFns); - suite = suite.parentSuite; + suite = suite.parentSuite!; } return { @@ -130,7 +163,7 @@ export default function(j$) { }; }; - const getSpecName = function(spec, suite) { + const getSpecName = function(spec: Spec, suite: Suite) { const fullName = [spec.description]; const suiteFullName = suite.getFullName(); @@ -173,27 +206,18 @@ export default function(j$) { return seed; }; - function queueRunnerFactory(options) { + const queueRunnerFactory = (options: QueueRunnerOptions) => { options.clearTimeout = realClearTimeout; - options.fail = self.fail; + options.fail = this.fail; options.setTimeout = realSetTimeout; return queueRunner(options); - } - - const topSuite = new j$.Suite({ - id: getNextSuiteId(), - getTestPath() { - return j$.testPath; - }, - }); - - currentDeclarationSuite = topSuite; + }; this.topSuite = function() { return topSuite; }; - const uncaught = err => { + const uncaught = (err: Error) => { if (currentSpec) { currentSpec.onException(err); currentSpec.cancel(); @@ -203,8 +227,8 @@ export default function(j$) { } }; - let oldListenersException; - let oldListenersRejection; + let oldListenersException: NodeJS.UncaughtExceptionListener[]; + let oldListenersRejection: NodeJS.UnhandledRejectionListener[]; const executionSetup = function() { // Need to ensure we are the only ones handling these exceptions. oldListenersException = process.listeners('uncaughtException').slice(); @@ -315,7 +339,7 @@ export default function(j$) { return spyRegistry.spyOn.apply(spyRegistry, arguments); }; - const suiteFactory = function(description) { + const suiteFactory = function(description: string) { const suite = new j$.Suite({ id: getNextSuiteId(), description, @@ -329,7 +353,7 @@ export default function(j$) { return suite; }; - this.describe = function(description, specDefinitions) { + this.describe = function(description: string, specDefinitions) { const suite = suiteFactory(description); if (specDefinitions === undefined) { throw new Error( @@ -361,7 +385,7 @@ export default function(j$) { return suite; }; - const focusedRunnables = []; + const focusedRunnables: string[] = []; this.fdescribe = function(description, specDefinitions) { const suite = suiteFactory(description); @@ -374,12 +398,12 @@ export default function(j$) { return suite; }; - function addSpecsToSuite(suite, specDefinitions) { + const addSpecsToSuite = (suite: Suite, specDefinitions: Function) => { const parentSuite = currentDeclarationSuite; parentSuite.addChild(suite); currentDeclarationSuite = suite; - let declarationError = null; + let declarationError: null | Error = null; try { specDefinitions.call(suite); } catch (e) { @@ -387,20 +411,20 @@ export default function(j$) { } if (declarationError) { - self.it('encountered a declaration exception', () => { + this.it('encountered a declaration exception', () => { throw declarationError; }); } currentDeclarationSuite = parentSuite; - } + }; - function findFocusedAncestor(suite) { + function findFocusedAncestor(suite: Suite) { while (suite) { if (suite.isFocused) { return suite.id; } - suite = suite.parentSuite; + suite = suite.parentSuite!; } return null; @@ -418,13 +442,18 @@ export default function(j$) { } } - const specFactory = function(description, fn, suite, timeout) { + const specFactory = ( + description: string, + fn: Function, + suite: Suite, + timeout?: number, + ) => { totalSpecsDefined++; const spec = new j$.Spec({ id: getNextSpecId(), beforeAndAfterFns: beforeAndAfterFns(suite), resultCallback: specResultCallback, - getSpecName(spec) { + getSpecName(spec: Spec) { return getSpecName(spec, suite); }, getTestPath() { @@ -445,19 +474,19 @@ export default function(j$) { throwOnExpectationFailure, }); - if (!self.specFilter(spec)) { + if (!this.specFilter(spec)) { spec.disable(); } return spec; - function specResultCallback(result) { + function specResultCallback(result: SpecResult) { clearResourcesForRunnable(spec.id); currentSpec = null; reporter.specDone(result); } - function specStarted(spec) { + function specStarted(spec: Spec) { currentSpec = spec; defaultResourcesForRunnable(spec.id, suite.id); reporter.specStarted(spec.result); @@ -495,18 +524,18 @@ export default function(j$) { if (currentSpec !== null) { throw new Error( 'Tests cannot be nested. Test `' + - spec.description + - '` cannot run because it is nested within `' + - currentSpec.description + - '`.', + spec.description + + '` cannot run because it is nested within `' + + currentSpec.description + + '`.', ); } currentDeclarationSuite.addChild(spec); return spec; }; - this.xit = function() { - const spec = this.it.apply(this, arguments); + this.xit = function(...args: any[]) { + const spec = this.it.apply(this, args); spec.pend('Temporarily disabled with xit'); return spec; }; @@ -520,7 +549,11 @@ export default function(j$) { ); } - const spec = specFactory(description, () => {}, currentDeclarationSuite); + const spec = specFactory( + description, + () => {}, + currentDeclarationSuite, + ); spec.todo(); currentDeclarationSuite.addChild(spec); return spec; @@ -603,7 +636,7 @@ export default function(j$) { expected: '', actual: '', message, - error: checkIsError ? error : new Error(message), + error: checkIsError ? error : new Error(message!), }); }; } diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index 82f50d99ec99..6b5f15f96e6a 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -29,6 +29,9 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ +import {SpecResult} from './Spec'; +import Suite from './Suite'; +import Timer from './Timer'; const noopTimer = { start() {}, @@ -42,20 +45,20 @@ export default class JsApiReporter { finished: boolean; runDetails: unknown; jasmineStarted: () => void; - jasmineDone: (runDetails: unknown) => void; + jasmineDone: (runDetails: SpecResult) => void; status: () => unknown; executionTime: () => unknown; - suiteStarted: (result: unknown) => void; - suiteDone: (result: unknown) => void; - suiteResults: (index: number, length: number) => unknown[]; - suites: () => unknown; + suiteStarted: (result: Suite) => void; + suiteDone: (result: Suite) => void; + suiteResults: (index: number, length: number) => Suite[]; + suites: () => {[key: string]: Suite}; - specResults: (index: number, length: number) => unknown[]; - specDone: (result: unknown) => void; - specs: () => unknown; + specResults: (index: number, length: number) => SpecResult[]; + specDone: (result: SpecResult) => void; + specs: () => SpecResult[]; - constructor(options: {timer?: unknown}) { + constructor(options: {timer?: Timer}) { const timer = options.timer || noopTimer; let status = 'loaded'; @@ -69,9 +72,9 @@ export default class JsApiReporter { timer.start(); }; - let executionTime; + let executionTime: number; - function validateAfterAllExceptions({failedExpectations}) { + function validateAfterAllExceptions({failedExpectations}: SpecResult) { if (failedExpectations && failedExpectations.length > 0) { throw failedExpectations[0]; } @@ -89,14 +92,14 @@ export default class JsApiReporter { return status; }; - const suites = []; - const suites_hash = {}; + const suites: Suite[] = []; + const suites_hash: {[key: string]: Suite} = {}; - this.suiteStarted = function(result) { + this.suiteStarted = function(result: Suite) { suites_hash[result.id] = result; }; - this.suiteDone = function(result) { + this.suiteDone = function(result: Suite) { storeSuite(result); }; @@ -104,7 +107,7 @@ export default class JsApiReporter { return suites.slice(index, index + length); }; - function storeSuite(result) { + function storeSuite(result: Suite) { suites.push(result); suites_hash[result.id] = result; } @@ -113,7 +116,7 @@ export default class JsApiReporter { return suites_hash; }; - const specs = []; + const specs: SpecResult[] = []; this.specDone = function(result) { specs.push(result); diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index d77cf2d31ae3..abbfe4966c22 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -28,13 +28,14 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import {Reporter} from '../types'; export default class ReportDispatcher { - addReporter: (reporter: unknown) => void; + addReporter: (reporter: Reporter) => void; provideFallbackReporter: (reporter: unknown) => void; clearReporters: () => void; - constructor(methods: Array) { + constructor(methods: Array) { const dispatchedMethods = methods || []; for (let i = 0; i < dispatchedMethods.length; i++) { @@ -46,7 +47,7 @@ export default class ReportDispatcher { })(method); } - let reporters = []; + let reporters: Reporter[] = []; let fallbackReporter = null; this.addReporter = function(reporter) { diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index 8183c213943a..94fe03b49cd8 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -31,56 +31,67 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable sort-keys */ import {AssertionError} from 'assert'; +import {Config, TestResult} from '@jest/types'; import ExpectationFailed from '../ExpectationFailed'; -import expectationResultFactory from '../expectationResultFactory'; +import expectationResultFactory, { + Options as ExpectationResultFactoryOptions, +} from '../expectationResultFactory'; import assertionErrorMessage from '../assertionErrorMessage'; -import {SpecResult} from '../reporter'; +import queueRunner, {QueueableFn} from '../queueRunner'; export type Attributes = { - id: unknown; - resultCallback: (result: SpecResult) => void; + id: string; + resultCallback: (result: Spec['result']) => void; description: string; throwOnExpectationFailure: unknown; - getTestPath: () => unknown; - queueableFn: unknown; - beforeAndAfterFns: unknown; - userContext: unknown; + getTestPath: () => Config.Path; + queueableFn: QueueableFn; + beforeAndAfterFns: () => {befores: QueueableFn[]; afters: QueueableFn[]}; + userContext: () => unknown; onStart: (context: Spec) => void; - getSpecName: () => string; - queueRunnerFactory: () => unknown; + getSpecName: (spec: Spec) => string; + queueRunnerFactory: typeof queueRunner; +}; + +export type SpecResult = { + id: string; + description: string; + fullName: string; + duration?: TestResult.Milliseconds; + failedExpectations: Array; + testPath: Config.Path; + passedExpectations: ReturnType[]; + pendingReason: string; + status: TestResult.Status; + __callsite?: { + getColumnNumber: () => number; + getLineNumber: () => number; + }; }; export default class Spec { - id: unknown; + id: string; description: string; - resultCallback: () => unknown; - queueableFn: unknown; - beforeAndAfterFns: () => {befores: unknown[]; afters: unknown[]}; + resultCallback: (result: SpecResult) => void; + queueableFn: QueueableFn; + beforeAndAfterFns: () => {befores: QueueableFn[]; afters: QueueableFn[]}; userContext: () => unknown; - onStart: () => unknown; + onStart: (spec: Spec) => void; getSpecName: (spec: Spec) => string; - queueRunnerFactory: () => unknown; + queueRunnerFactory: typeof queueRunner; throwOnExpectationFailure: boolean; initError: Error; - result: { - id: unknown; - description: unknown; - fullName: string; - failedExpectations: []; - testPath: unknown; - passedExpectations: unknown[]; - pendingReason: string; - }; - disabled: boolean; - currentRun: unknown; - markedTodo: boolean; - markedPending: boolean; - expand: boolean; + result: SpecResult; + disabled?: boolean; + currentRun?: ReturnType; + markedTodo?: boolean; + markedPending?: boolean; + expand?: boolean; static pendingSpecExceptionMessage = '=> marked Pending'; - static isPendingSpecException(e: unknown) { + static isPendingSpecException(e: Error) { return !!( e && e.toString && @@ -134,7 +145,11 @@ export default class Spec { }; } - addExpectationResult(passed, data, isError) { + addExpectationResult( + passed: boolean, + data: ExpectationResultFactoryOptions, + isError?: boolean, + ) { const expectationResult = expectationResultFactory(data, this.initError); if (passed) { this.result.passedExpectations.push(expectationResult); @@ -147,7 +162,7 @@ export default class Spec { } } - execute(onComplete, enabled) { + execute(onComplete: Function, enabled: boolean) { const self = this; this.onStart(this); @@ -171,11 +186,14 @@ export default class Spec { self.onException.apply(self, arguments); }, userContext: this.userContext(), + setTimeout, + clearTimeout, + fail: () => {}, }); this.currentRun.then(() => complete(true)); - function complete(enabledAgain) { + function complete(enabledAgain: boolean) { self.result.status = self.status(enabledAgain); self.resultCallback(self.result); @@ -185,13 +203,13 @@ export default class Spec { } } - cancelcancel() { + cancel() { if (this.currentRun) { this.currentRun.cancel(); } } - onExceptiononException(error) { + onException(error: ExpectationFailed | AssertionError) { if (Spec.isPendingSpecException(error)) { this.pend(extractCustomPendingMessage(error)); return; @@ -222,7 +240,7 @@ export default class Spec { this.disabled = true; } - pend(message) { + pend(message: string) { this.markedPending = true; if (message) { this.result.pendingReason = message; @@ -238,7 +256,7 @@ export default class Spec { return this.result; } - status(enabled: boolean) { + status(enabled?: boolean) { if (this.disabled || enabled === false) { return 'disabled'; } @@ -267,7 +285,7 @@ export default class Spec { } } -const extractCustomPendingMessage = function(e) { +const extractCustomPendingMessage = function(e: Error) { const fullMessage = e.toString(); const boilerplateStart = fullMessage.indexOf( Spec.pendingSpecExceptionMessage, diff --git a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts index 372d66cf5168..d86703aee41d 100644 --- a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts +++ b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts @@ -31,25 +31,22 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export default class SpyStrategy { identity: () => string; - exec: () => unknown; + exec: (...args: any[]) => unknown; callThrough: () => unknown; returnValue: (value: unknown) => unknown; returnValues: () => unknown; - throwError: (something: unknown) => unknown; - callFake: (fn: unknown) => unknown; - stub: (fn: unknown) => unknown; + throwError: (something: string | Error) => unknown; + callFake: (fn: Function) => unknown; + stub: (fn: Function) => unknown; - constructor(options?: { - name: string; - fn: () => unknown; - getSpy: () => unknown; - }) { - options = options || {}; - - const identity = options.name || 'unknown'; - const originalFn = options.fn || function() {}; - const getSpy = options.getSpy || function() {}; - let plan = function() {}; + constructor({ + name = 'unknown', + fn = function() {}, + getSpy = function() {}, + }: {name?: string; fn?: Function; getSpy?: () => unknown} = {}) { + const identity = name; + const originalFn = fn; + let plan: Function = function() {}; this.identity = function() { return identity; @@ -98,7 +95,7 @@ export default class SpyStrategy { return getSpy(); }; - this.stub = function(fn) { + this.stub = function(_fn) { plan = function() {}; return getSpy(); }; diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 5f02ac90676a..4b0a5d89fb9d 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -31,36 +31,45 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable sort-keys */ import {convertDescriptorToString} from 'jest-util'; +import {Config} from '@jest/types'; import ExpectationFailed from '../ExpectationFailed'; -import expectationResultFactory from '../expectationResultFactory'; +import expectationResultFactory, { + Options as ExpectationResultFactoryOptions, +} from '../expectationResultFactory'; +import {QueueableFn} from '../queueRunner'; + +type SuiteResult = { + id: string; + description: string; + fullName: string; + failedExpectations: Array>; + testPath: Config.Path; + status?: string; +}; export default class Suite { - id: unknown; - parentSuite: unknown; - description: unknown; - throwOnExpectationFailure: unknown; - beforeFns: unknown; - afterFns: unknown; - beforeAllFns: unknown; - afterAllFns: unknown; + id: string; + parentSuite?: Suite; + description: string; + throwOnExpectationFailure: boolean; + beforeFns: QueueableFn[]; + afterFns: QueueableFn[]; + beforeAllFns: QueueableFn[]; + afterAllFns: QueueableFn[]; disabled: boolean; - children: unknown; - result: { - id: unknown; - description: unknown; - fullName: string; - failedExpectations: []; - testPath: unknown; - }; - markedPending: boolean; - sharedContext: unknown; + children: Suite[]; + result: SuiteResult; + sharedContext?: object; + markedPending: boolean = false; + markedTodo: boolean = false; + isFocused: boolean = false; constructor(attrs: { - id: unknown; - parentSuite: unknown; - description: unknown; - throwOnExpectationFailure: unknown; - getTestPath: () => unknown; + id: string; + parentSuite?: Suite; + description?: string; + throwOnExpectationFailure?: boolean; + getTestPath: () => Config.Path; }) { this.id = attrs.id; this.parentSuite = attrs.parentSuite; @@ -86,7 +95,7 @@ export default class Suite { getFullName() { const fullName = []; for ( - let parentSuite = this; + let parentSuite: Suite | undefined = this; parentSuite; parentSuite = parentSuite.parentSuite ) { @@ -99,23 +108,23 @@ export default class Suite { disable() { this.disabled = true; } - pend(message) { + pend(_message?: string) { this.markedPending = true; } - beforeEach(fn) { + beforeEach(fn: QueueableFn) { this.beforeFns.unshift(fn); } - beforeAll(fn) { + beforeAll(fn: QueueableFn) { this.beforeAllFns.push(fn); } - afterEach(fn) { + afterEach(fn: QueueableFn) { this.afterFns.unshift(fn); } - afterAll(fn) { + afterAll(fn: QueueableFn) { this.afterAllFns.unshift(fn); } - addChild(child) { + addChild(child: Suite) { this.children.push(child); } @@ -144,7 +153,7 @@ export default class Suite { } getResult() { - this.result.status = this.status(); + this.result.status! = this.status(); return this.result; } @@ -160,8 +169,8 @@ export default class Suite { return this.sharedUserContext(); } - onException() { - if (arguments[0] instanceof ExpectationFailed) { + onException(...args: Array) { + if (args[0] instanceof ExpectationFailed) { return; } @@ -177,14 +186,14 @@ export default class Suite { } else { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; - child.onException.apply(child, arguments); + child.onException.apply(child, args); } } } - addExpectationResult() { - if (isAfterAll(this.children) && isFailure(arguments)) { - const data = arguments[1]; + addExpectationResult(...args: ExpectationResultFactoryOptions[]) { + if (isAfterAll(this.children) && isFailure(args)) { + const data = args[1]; this.result.failedExpectations.push(expectationResultFactory(data)); if (this.throwOnExpectationFailure) { throw new ExpectationFailed(); @@ -193,7 +202,7 @@ export default class Suite { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; try { - child.addExpectationResult.apply(child, arguments); + child.addExpectationResult.apply(child, args); } catch (e) { // keep going } @@ -202,10 +211,10 @@ export default class Suite { } } -function isAfterAll(children) { +function isAfterAll(children: Suite[]) { return children && children[0] && children[0].result.status; } -function isFailure(args) { +function isFailure(args: unknown[]) { return !args[0]; } diff --git a/packages/jest-jasmine2/src/jasmine/Timer.ts b/packages/jest-jasmine2/src/jasmine/Timer.ts index a4ef52638082..fe6a8f9ec9fa 100644 --- a/packages/jest-jasmine2/src/jasmine/Timer.ts +++ b/packages/jest-jasmine2/src/jasmine/Timer.ts @@ -39,7 +39,7 @@ export default class Timer { start: () => void; elapsed: () => number; - constructor(options: {now?: () => number}) { + constructor(options?: {now?: () => number}) { options = options || {}; const now = options.now || defaultNow; diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index e15452c57827..07ce91d6e617 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -30,16 +30,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ -import CallTracker from './CallTracker'; - +import CallTracker, {Context} from './CallTracker'; import SpyStrategy from './SpyStrategy'; -type Spy = { +interface Spy extends Record { + (...args: any[]): unknown; and: SpyStrategy; - calls: SpyStrategy; -}; + calls: CallTracker; +} -function createSpy(name: string, originalFn: unknown): Spy { +function createSpy(name: string, originalFn: Function): Spy { const spyStrategy = new SpyStrategy({ name, fn: originalFn, @@ -48,14 +48,14 @@ function createSpy(name: string, originalFn: unknown): Spy { }, }); const callTracker = new CallTracker(); - const spy = function(this: unknown) { - const callData = { + const spy = function(this: unknown, ...args: any[]) { + const callData: Context = { object: this, args: Array.prototype.slice.apply(arguments), }; callTracker.track(callData); - const returnValue = spyStrategy.exec.apply(this, arguments); + const returnValue = spyStrategy.exec.apply(this, args); callData.returnValue = returnValue; return returnValue; diff --git a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts index 0aa19fe22b4d..ef9ad0507cc5 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts +++ b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts @@ -30,7 +30,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ -import {Jasmine} from '../types'; +import {Jasmine, $J} from '../types'; import createSpy from './createSpy'; import Env from './Env'; import JsApiReporter from './JsApiReporter'; @@ -40,16 +40,12 @@ import SpyRegistry from './spyRegistry'; import Suite from './Suite'; import Timer from './Timer'; -type $J = { - _DEFAULT_TIMEOUT_INTERVAL: number; -}; - -exports.create = function(createOptions: Object): $J { - const j$ = {...createOptions}; +const create = function(createOptions: Object): $J { + const j$: $J = {...createOptions}; j$._DEFAULT_TIMEOUT_INTERVAL = 5000; - j$.getEnv = function(options: Object) { + j$.getEnv = function(options: object) { const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; @@ -68,7 +64,7 @@ exports.create = function(createOptions: Object): $J { }; // Interface is a reserved word in strict mode, so can't export it as ESM -exports.interface = function(jasmine: Jasmine, env: any) { +const interface = function(jasmine: Jasmine, env: any) { const jasmineInterface = { describe(description: string, specDefinitions: Function) { return env.describe(description, specDefinitions); @@ -151,3 +147,5 @@ exports.interface = function(jasmine: Jasmine, env: any) { return jasmineInterface; }; + +export = {create, interface}; diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts index a70941edfa83..874b65d4fdb3 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -39,7 +39,7 @@ const formatErrorMsg = (domain: string, usage?: string) => { return (msg: string) => domain + ' : ' + msg + usageDefinition; }; -function isSpy(putativeSpy) { +function isSpy(putativeSpy: any) { if (!putativeSpy) { return false; } @@ -67,14 +67,11 @@ export default class SpyRegistry { accessType: keyof PropertyDescriptor, ) => unknown; - constructor(options?: {currentSpies: () => unknown[]}) { - options = options || {}; - const currentSpies = - options.currentSpies || - function() { - return []; - }; - + constructor({ + currentSpies = () => [], + }: { + currentSpies?: () => Array<{restoreObjectToOriginalState: () => void}>; + } = {}) { this.allowRespy = function(allow) { this.respy = allow; }; diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index a45d8a6ff9a5..0588f605099f 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -15,18 +15,22 @@ import co from 'co'; import isGeneratorFn from 'is-generator-fn'; import throat from 'throat'; import isError from './isError'; +import {$J, Jasmine} from './types'; function isPromise(obj: any) { return obj && typeof obj.then === 'function'; } -function promisifyLifeCycleFunction(originalFn, env) { - return function(fn: Promise | GeneratorFunction, timeout: number) { +function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { + return function( + fn: Promise | GeneratorFunction | undefined, + timeout: number, + ) { if (!fn) { return originalFn.call(env); } - const hasDoneCallback = fn.length > 0; + const hasDoneCallback = typeof fn === 'function' && fn.length > 0; if (hasDoneCallback) { // Jasmine will handle it @@ -43,12 +47,12 @@ function promisifyLifeCycleFunction(originalFn, env) { // We make *all* functions async and run `done` right away if they // didn't return a promise. - const asyncJestLifecycle = function(done) { + const asyncJestLifecycle = function(done: Function) { const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn; const returnValue = wrappedFn.call({}); if (isPromise(returnValue)) { - returnValue.then(done.bind(null, null), error => { + returnValue.then(done.bind(null, null), (error: Error) => { const {isError: checkIsError, message} = isError(error); if (message) { @@ -67,8 +71,8 @@ function promisifyLifeCycleFunction(originalFn, env) { // Similar to promisifyLifeCycleFunction but throws an error // when the return value is neither a Promise nor `undefined` -function promisifyIt(originalFn, env, jasmine) { - return function(specName, fn, timeout) { +function promisifyIt(originalFn: Global.It, env: Env, jasmine: Jasmine) { + return function(specName: string, fn, timeout?: number) { if (!fn) { const spec = originalFn.call(env, specName); spec.pend('not implemented'); @@ -89,12 +93,12 @@ function promisifyIt(originalFn, env, jasmine) { // https://crbug.com/v8/7142 extraError.stack = extraError.stack; - const asyncJestTest = function(done) { + const asyncJestTest = function(done: Function) { const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn; const returnValue = wrappedFn.call({}); if (isPromise(returnValue)) { - returnValue.then(done.bind(null, null), error => { + returnValue.then(done.bind(null, null), (error: Error) => { const {isError: checkIsError, message} = isError(error); if (message) { @@ -123,8 +127,12 @@ function promisifyIt(originalFn, env, jasmine) { }; } -function makeConcurrent(originalFn: Function, env, mutex: ReturnType) { - return function(specName, fn, timeout) { +function makeConcurrent( + originalFn: Function, + env, + mutex: ReturnType, +) { + return function(specName: string, fn: () => Promise, timeout: number) { if (env != null && !env.specFilter({getFullName: () => specName || ''})) { return originalFn.call(env, specName, () => Promise.resolve(), timeout); } diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index 5a7f9304544a..23639fa58cf8 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -8,17 +8,22 @@ import PCancelable from './PCancelable'; import pTimeout from './pTimeout'; -type Options = { - clearTimeout: (timeoutID: number) => void; - fail: () => void; +type Global = NodeJS.Global; + +export type Options = { + clearTimeout: (timeoutID: number) => void | Global['clearTimeout']; + fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array; - setTimeout: (func: () => void, delay: number) => number; + setTimeout: ( + func: () => void, + delay: number, + ) => number | Global['setTimeout']; userContext: any; }; -type QueueableFn = { - fn: (next: () => void) => void; +export type QueueableFn = { + fn: (next: (...args: any[]) => void) => void; timeout?: () => number; initError?: Error; }; @@ -30,7 +35,7 @@ export default function queueRunner(options: Options) { const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => { let promise = new Promise(resolve => { - const next = function(...args: unknown[]) { + const next = function(...args: any[]) { const err = args[0]; if (err) { options.fail.apply(null, args); @@ -38,7 +43,7 @@ export default function queueRunner(options: Options) { resolve(); }; - next.fail = function(...args: unknown[]) { + next.fail = function(...args: any[]) { options.fail.apply(null, args); resolve(); }; diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 60057aad78f4..6bebec3ae75c 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -7,23 +7,8 @@ import {Config, TestResult} from '@jest/types'; import {formatResultsErrors} from 'jest-message-util'; - -export type Suite = { - description: string; -}; - -export type SpecResult = { - __callsite?: { - getColumnNumber: () => number; - getLineNumber: () => number; - }; - description: string; - duration?: TestResult.Milliseconds; - failedExpectations: Array; - fullName: string; - id: string; - status: TestResult.Status; -}; +import Spec, {SpecResult} from './jasmine/Spec'; +import Suite from './jasmine/Suite'; type Microseconds = number; @@ -52,7 +37,7 @@ export default class Jasmine2Reporter { this._startTimes = new Map(); } - specStarted(spec: {id: string}) { + specStarted(spec: Spec) { this._startTimes.set(spec.id, Date.now()); } diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index d977a78a10d1..79c32824eae0 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -12,8 +12,7 @@ import { SnapshotState, addSerializer, } from 'jest-snapshot'; -import {SpecResult} from './reporter'; -import JasmineSpec, {Attributes} from './jasmine/Spec'; +import JasmineSpec, {Attributes, SpecResult} from './jasmine/Spec'; export type SetupOptions = { config: Config.ProjectConfig; @@ -36,6 +35,7 @@ const addSuppressedErrors = (result: SpecResult) => { // passing error for custom test reporters error, expected: '', + matcherName: '', message: error.message, passed: false, stack: error.stack, @@ -62,7 +62,7 @@ const patchJasmine = () => { class Spec extends realSpec { constructor(attr: Attributes) { const resultCallback = attr.resultCallback; - attr.resultCallback = function(result: SpecResult) { + attr.resultCallback = function(result: Spec['result']) { addSuppressedErrors(result); addAssertionErrors(result); resultCallback.call(attr, result); diff --git a/packages/jest-jasmine2/src/treeProcessor.ts b/packages/jest-jasmine2/src/treeProcessor.ts index c10e362e69de..106a2c73666e 100644 --- a/packages/jest-jasmine2/src/treeProcessor.ts +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ +import Suite from './jasmine/Suite'; type Options = { nodeComplete: (suite: TreeNode) => void; @@ -13,16 +14,7 @@ type Options = { tree: TreeNode; }; -type TreeNode = { - afterAllFns: Array; - beforeAllFns: Array; - disabled?: boolean; - execute: (onComplete: () => void, enabled: boolean) => void; - id: string; - onException: (error: Error) => void; - sharedUserContext: () => any; - children?: Array; -}; +type TreeNode = Suite; export default function treeProcessor(options: Options) { const { diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index 795c5fc1c415..83349e8cd3b4 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -5,7 +5,17 @@ * LICENSE file in the root directory of this source tree. */ +import {Config} from '@jest/types'; import expect from 'expect'; +import Spec from './jasmine/Spec'; +import JsApiReporter from './jasmine/JsApiReporter'; +import Jasmine2Reporter from './reporter'; +import Timer from './jasmine/Timer'; +import Env from './jasmine/Env'; +import createSpy from './jasmine/createSpy'; +import ReportDispatcher from './jasmine/ReportDispatcher'; +import SpyRegistry from './jasmine/spyRegistry'; +import Suite from './jasmine/Suite'; // TODO Add expect types to @jest/types or leave it here // Borrowed from "expect" @@ -26,10 +36,29 @@ export type RawMatcherFn = ( ) => ExpectationResult; // -------END------- +export type Reporter = JsApiReporter | Jasmine2Reporter; export type Jasmine = { - Spec: unknown; + Spec: typeof Spec; + JsApiReporter: typeof JsApiReporter; + Timer: typeof Timer; } & typeof expect; +export interface $J extends NodeJS.Global { + _DEFAULT_TIMEOUT_INTERVAL: number; + currentEnv_: ReturnType['prototype']; + getEnv: (options: object) => ReturnType; + createSpy: typeof createSpy; + Env: ReturnType; + JsApiReporter: typeof JsApiReporter; + ReportDispatcher: typeof ReportDispatcher; + Spec: typeof Spec; + SpyRegistry: typeof SpyRegistry; + Suite: typeof Suite; + Timer: typeof Timer; + version: string; + testPath: Config.Path; +} + declare global { module NodeJS { interface Global { diff --git a/packages/jest-types/src/TestResult.ts b/packages/jest-types/src/TestResult.ts index 857751e6a9f0..3c7c480c4252 100644 --- a/packages/jest-types/src/TestResult.ts +++ b/packages/jest-types/src/TestResult.ts @@ -80,13 +80,14 @@ export type SerializableError = { }; export type FailedAssertion = { - matcherName: string; + matcherName?: string; message?: string; actual?: any; pass?: boolean; expected?: any; isNot?: boolean; stack?: string; + error?: any; }; export type AssertionLocation = { diff --git a/packages/jest-util/src/convertDescriptorToString.ts b/packages/jest-util/src/convertDescriptorToString.ts index fb36658fde85..53141efd0682 100644 --- a/packages/jest-util/src/convertDescriptorToString.ts +++ b/packages/jest-util/src/convertDescriptorToString.ts @@ -8,7 +8,7 @@ // See: https://github.com/facebook/jest/pull/5154 export default function convertDescriptorToString( descriptor: string | Function, -): string { +): string | undefined { if ( typeof descriptor === 'string' || typeof descriptor === 'number' || From d00496af2b69d557aba6b70748337d930ad5074c Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Wed, 27 Feb 2019 19:52:08 +0500 Subject: [PATCH 08/25] Some tweaks --- packages/jest-jasmine2/src/PCancelable.ts | 7 +++-- .../src/__tests__/hooksError.test.ts | 5 +++- .../src/assertionErrorMessage.ts | 15 ++++------- packages/jest-jasmine2/src/index.ts | 26 ++++++++++-------- .../src/jasmine/ReportDispatcher.ts | 7 ++--- packages/jest-jasmine2/src/jasmine/Spec.ts | 14 +++++----- packages/jest-jasmine2/src/jasmine/Suite.ts | 2 ++ .../jest-jasmine2/src/jasmineAsyncInstall.ts | 27 ++++++++++++------- packages/jest-jasmine2/src/jestExpect.ts | 13 +++++++-- packages/jest-jasmine2/src/queueRunner.ts | 9 +++---- .../jest-jasmine2/src/setup_jest_globals.ts | 2 +- packages/jest-jasmine2/src/types.ts | 12 ++++++++- packages/jest-types/src/Global.ts | 5 +++- 13 files changed, 91 insertions(+), 53 deletions(-) diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index 0751e95a269f..34f109313d20 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -19,6 +19,7 @@ class PCancelable extends Promise { private _pending: boolean; private _canceled: boolean; private _cancel?: Function; + // @ts-ignore private _reject: (reason?: any) => void; private _promise: Promise; @@ -35,9 +36,11 @@ class PCancelable extends Promise { // @ts-ignore constructor(executor: (onCancel, resolve, reject) => any) { + // @ts-ignore this._pending = true; + // @ts-ignore this._canceled = false; - + // @ts-ignore this._promise = new Promise((resolve, reject) => { this._reject = reject; @@ -45,7 +48,7 @@ class PCancelable extends Promise { (fn: Function) => { this._cancel = fn; }, - (val: unknown) => { + (val: T) => { this._pending = false; resolve(val); }, diff --git a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts index 1de5568e261d..e760b48b7b1c 100644 --- a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts @@ -5,9 +5,12 @@ * LICENSE file in the root directory of this source tree. */ +export type SharedHookType = 'afterAll' | 'beforeAll'; +export type HookType = SharedHookType | 'afterEach' | 'beforeEach'; + describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( '%s hooks error throwing', - fn => { + (fn: HookType) => { test.each([ ['String'], [1], diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index 5fcb42bbb383..be67c2d8bdcc 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -7,19 +7,11 @@ import {diff, printReceived, printExpected} from 'jest-matcher-utils'; import chalk from 'chalk'; +import {AssertionErrorWithStack} from './types'; // TODO replace with import {DiffOptions} from 'jest-matcher-utils'; type DiffOptions = Parameters[2]; -type AssertionError = { - actual: string | null; - expected: string | null; - generatedMessage: boolean; - message: string; - name: string; - operator: string | null; - stack: string; -}; const assertOperatorsMap: {[key: string]: string} = { '!=': 'notEqual', @@ -89,7 +81,10 @@ const assertMatcherHint = (operator: string | null, operatorName: string) => { return message; }; -function assertionErrorMessage(error: AssertionError, options: DiffOptions) { +function assertionErrorMessage( + error: AssertionErrorWithStack, + options: DiffOptions, +) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); const hasCustomMessage = !generatedMessage; diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index fab7298b10f2..c3eb5344b5bb 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -43,7 +43,7 @@ async function jasmine2( // in a future version if (config.testLocationInResults === true) { const originalIt = environment.global.it; - environment.global.it = (...args) => { + environment.global.it = (...args: any[]) => { const stack = getCallsite(1, runtime.getSourceMaps()); const it = originalIt(...args); @@ -53,7 +53,7 @@ async function jasmine2( }; const originalXit = environment.global.xit; - environment.global.xit = (...args) => { + environment.global.xit = (...args: any[]) => { const stack = getCallsite(1, runtime.getSourceMaps()); const xit = originalXit(...args); @@ -63,7 +63,7 @@ async function jasmine2( }; const originalFit = environment.global.fit; - environment.global.fit = (...args) => { + environment.global.fit = (...args: any[]) => { const stack = getCallsite(1, runtime.getSourceMaps()); const fit = originalFit(...args); @@ -145,7 +145,9 @@ async function jasmine2( testPath, }); - config.setupFilesAfterEnv.forEach(path => runtime.requireModule(path)); + config.setupFilesAfterEnv.forEach((path: Config.Path) => + runtime.requireModule(path), + ); if (globalConfig.enabledTestsMap) { env.specFilter = (spec: Spec) => { @@ -172,13 +174,15 @@ const addSnapshotData = ( results: TestResult.TestResult, snapshotState: typeof SnapshotState.prototype, ) => { - results.testResults.forEach(({fullName, status}) => { - if (status === 'pending' || status === 'failed') { - // if test is skipped or failed, we don't want to mark - // its snapshots as obsolete. - snapshotState.markSnapshotsAsCheckedForTest(fullName); - } - }); + results.testResults.forEach( + ({fullName, status}: TestResult.AssertionResult) => { + if (status === 'pending' || status === 'failed') { + // if test is skipped or failed, we don't want to mark + // its snapshots as obsolete. + snapshotState.markSnapshotsAsCheckedForTest(fullName); + } + }, + ); const uncheckedCount = snapshotState.getUncheckedCount(); const uncheckedKeys = snapshotState.getUncheckedKeys(); diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index abbfe4966c22..a39eebb8ea83 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -34,8 +34,9 @@ export default class ReportDispatcher { addReporter: (reporter: Reporter) => void; provideFallbackReporter: (reporter: unknown) => void; clearReporters: () => void; + [key: string]: any; - constructor(methods: Array) { + constructor(methods: Array) { const dispatchedMethods = methods || []; for (let i = 0; i < dispatchedMethods.length; i++) { @@ -48,7 +49,7 @@ export default class ReportDispatcher { } let reporters: Reporter[] = []; - let fallbackReporter = null; + let fallbackReporter: Reporter | null = null; this.addReporter = function(reporter) { reporters.push(reporter); @@ -64,7 +65,7 @@ export default class ReportDispatcher { return this; - function dispatch(method: string, args) { + function dispatch(method: string, args: any) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index 94fe03b49cd8..8c0690007258 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -39,6 +39,7 @@ import expectationResultFactory, { } from '../expectationResultFactory'; import assertionErrorMessage from '../assertionErrorMessage'; import queueRunner, {QueueableFn} from '../queueRunner'; +import {AssertionErrorWithStack} from '../types'; export type Attributes = { id: string; @@ -134,6 +135,7 @@ export default class Spec { this.queueableFn.initError = this.initError; + // @ts-ignore this.result = { id: this.id, description: this.description, @@ -183,6 +185,7 @@ export default class Spec { this.currentRun = this.queueRunnerFactory({ queueableFns: allFns, onException() { + // @ts-ignore self.onException.apply(self, arguments); }, userContext: this.userContext(), @@ -209,7 +212,7 @@ export default class Spec { } } - onException(error: ExpectationFailed | AssertionError) { + onException(error: ExpectationFailed | AssertionErrorWithStack) { if (Spec.isPendingSpecException(error)) { this.pend(extractCustomPendingMessage(error)); return; @@ -219,10 +222,6 @@ export default class Spec { return; } - if (error instanceof AssertionError) { - error = assertionErrorMessage(error, {expand: this.expand}); - } - this.addExpectationResult( false, { @@ -230,7 +229,10 @@ export default class Spec { passed: false, expected: '', actual: '', - error, + error: + error instanceof AssertionError + ? assertionErrorMessage(error, {expand: this.expand}) + : error, }, true, ); diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 4b0a5d89fb9d..cb3354878806 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -209,6 +209,8 @@ export default class Suite { } } } + + execute(..._args: any[]) {} } function isAfterAll(children: Suite[]) { diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 0588f605099f..984d5cab77a9 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -16,6 +16,12 @@ import isGeneratorFn from 'is-generator-fn'; import throat from 'throat'; import isError from './isError'; import {$J, Jasmine} from './types'; +import Spec from './jasmine/Spec'; + +interface DoneFn { + (): void; + fail: (error: Error) => void; +} function isPromise(obj: any) { return obj && typeof obj.then === 'function'; @@ -23,7 +29,7 @@ function isPromise(obj: any) { function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { return function( - fn: Promise | GeneratorFunction | undefined, + fn: () => Promise | GeneratorFunction | undefined, timeout: number, ) { if (!fn) { @@ -47,9 +53,9 @@ function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { // We make *all* functions async and run `done` right away if they // didn't return a promise. - const asyncJestLifecycle = function(done: Function) { + const asyncJestLifecycle = function(done: DoneFn) { const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn; - const returnValue = wrappedFn.call({}); + const returnValue = wrappedFn.call({}) as Promise; if (isPromise(returnValue)) { returnValue.then(done.bind(null, null), (error: Error) => { @@ -71,8 +77,8 @@ function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { // Similar to promisifyLifeCycleFunction but throws an error // when the return value is neither a Promise nor `undefined` -function promisifyIt(originalFn: Global.It, env: Env, jasmine: Jasmine) { - return function(specName: string, fn, timeout?: number) { +function promisifyIt(originalFn: Function, env: $J['Env'], jasmine: Jasmine) { + return function(specName: string, fn: Function, timeout?: number) { if (!fn) { const spec = originalFn.call(env, specName); spec.pend('not implemented'); @@ -93,7 +99,7 @@ function promisifyIt(originalFn: Global.It, env: Env, jasmine: Jasmine) { // https://crbug.com/v8/7142 extraError.stack = extraError.stack; - const asyncJestTest = function(done: Function) { + const asyncJestTest = function(done: DoneFn) { const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn; const returnValue = wrappedFn.call({}); @@ -106,7 +112,7 @@ function promisifyIt(originalFn: Global.It, env: Env, jasmine: Jasmine) { } if (jasmine.Spec.isPendingSpecException(error)) { - env.pending(message); + env.pending(message!); done(); } else { done.fail(checkIsError ? error : extraError); @@ -129,11 +135,14 @@ function promisifyIt(originalFn: Global.It, env: Env, jasmine: Jasmine) { function makeConcurrent( originalFn: Function, - env, + env: $J['Env'], mutex: ReturnType, ) { return function(specName: string, fn: () => Promise, timeout: number) { - if (env != null && !env.specFilter({getFullName: () => specName || ''})) { + if ( + env != null && + !env.specFilter({getFullName: () => specName || ''} as Spec) + ) { return originalFn.call(env, specName, () => Promise.resolve(), timeout); } diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index 109489b4aa86..57810c84d833 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -55,8 +55,17 @@ export default (config: {expand: boolean}) => { const negativeCompare = result.negativeCompare || result.compare; return this.isNot - ? negativeCompare.apply(null, args) - : result.compare.apply(null, args); + ? negativeCompare.apply( + null, + // @ts-ignore + args, + ) + : // @ts-ignore + result.compare.apply( + null, + // @ts-ignore + args, + ); }; }); diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index 23639fa58cf8..6ff21325d025 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -15,10 +15,7 @@ export type Options = { fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array; - setTimeout: ( - func: () => void, - delay: number, - ) => number | Global['setTimeout']; + setTimeout: Global['setTimeout']; userContext: any; }; @@ -35,7 +32,7 @@ export default function queueRunner(options: Options) { const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => { let promise = new Promise(resolve => { - const next = function(...args: any[]) { + const next = function(...args: [Error]) { const err = args[0]; if (err) { options.fail.apply(null, args); @@ -43,7 +40,7 @@ export default function queueRunner(options: Options) { resolve(); }; - next.fail = function(...args: any[]) { + next.fail = function(...args: [Error]) { options.fail.apply(null, args); resolve(); }; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 79c32824eae0..6a08eafba972 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -62,7 +62,7 @@ const patchJasmine = () => { class Spec extends realSpec { constructor(attr: Attributes) { const resultCallback = attr.resultCallback; - attr.resultCallback = function(result: Spec['result']) { + attr.resultCallback = function(result: SpecResult) { addSuppressedErrors(result); addAssertionErrors(result); resultCallback.call(attr, result); diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index 83349e8cd3b4..fba2d87d77c4 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +import {AssertionError} from 'assert'; import {Config} from '@jest/types'; import expect from 'expect'; import Spec from './jasmine/Spec'; @@ -17,6 +18,10 @@ import ReportDispatcher from './jasmine/ReportDispatcher'; import SpyRegistry from './jasmine/spyRegistry'; import Suite from './jasmine/Suite'; +export interface AssertionErrorWithStack extends AssertionError { + stack: string; +} + // TODO Add expect types to @jest/types or leave it here // Borrowed from "expect" // -------START------- @@ -48,7 +53,7 @@ export interface $J extends NodeJS.Global { currentEnv_: ReturnType['prototype']; getEnv: (options: object) => ReturnType; createSpy: typeof createSpy; - Env: ReturnType; + Env: ReturnType['prototype']; JsApiReporter: typeof JsApiReporter; ReportDispatcher: typeof ReportDispatcher; Spec: typeof Spec; @@ -60,6 +65,11 @@ export interface $J extends NodeJS.Global { } declare global { + /* namespace jest { + interface Global { + jasmine: Jasmine; + } + }*/ module NodeJS { interface Global { jasmine: Jasmine; diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index 1a782eaaa386..a191a754799a 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -48,7 +48,7 @@ export interface Describe extends DescribeBase { skip: ItBase; } -export interface Global extends NodeJS.Global { +export interface Global { it: It; test: ItConcurrent; fit: ItBase; @@ -60,6 +60,9 @@ export interface Global extends NodeJS.Global { } declare global { + namespace jest { + interface _Global extends Global {} + } module NodeJS { interface Global { it: It; From eee83393533bfb7fc6fa49d63cef9e54de83c4e7 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Fri, 1 Mar 2019 17:46:32 +0500 Subject: [PATCH 09/25] Small tweaks --- packages/jest-jasmine2/src/jasmine/Env.ts | 4 ++-- .../jest-jasmine2/src/jasmine/ReportDispatcher.ts | 2 +- packages/jest-jasmine2/src/jasmine/createSpy.ts | 2 +- packages/jest-jasmine2/src/jasmine/jasmineLight.ts | 2 +- packages/jest-jasmine2/src/jasmineAsyncInstall.ts | 8 ++++++-- packages/jest-jasmine2/src/pTimeout.ts | 4 ++-- packages/jest-jasmine2/src/queueRunner.ts | 2 +- packages/jest-jasmine2/src/types.ts | 13 ++++++------- 8 files changed, 20 insertions(+), 17 deletions(-) diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 01dfc79f39c4..b73f4c808b18 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -39,7 +39,7 @@ import queueRunner, { import treeProcessor from '../treeProcessor'; import isError from '../isError'; import assertionErrorMessage from '../assertionErrorMessage'; -import {$J, Reporter} from '../types'; +import {$J, AssertionErrorWithStack, Reporter} from "../types"; import Spec, {SpecResult} from './Spec'; import Suite from './Suite'; @@ -50,7 +50,7 @@ export default function(j$: $J) { throwOnExpectationFailure: (value: unknown) => void; catchingExceptions: () => boolean; topSuite: () => Suite; - fail: (error: Error | AssertionError) => void; + fail: (error: Error | AssertionErrorWithStack) => void; pending: (message: string) => void; afterAll: (afterAllFunction: QueueableFn['fn'], timeout?: number) => void; fit: (description: string, fn: QueueableFn['fn'], timeout?: number) => void; diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index a39eebb8ea83..1f74eedd9126 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -32,7 +32,7 @@ import {Reporter} from '../types'; export default class ReportDispatcher { addReporter: (reporter: Reporter) => void; - provideFallbackReporter: (reporter: unknown) => void; + provideFallbackReporter: (reporter: Reporter) => void; clearReporters: () => void; [key: string]: any; diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index 07ce91d6e617..f4a8b704f078 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -48,7 +48,7 @@ function createSpy(name: string, originalFn: Function): Spy { }, }); const callTracker = new CallTracker(); - const spy = function(this: unknown, ...args: any[]) { + const spy = function(this: {[key: string]: any}, ...args: any[]) { const callData: Context = { object: this, args: Array.prototype.slice.apply(arguments), diff --git a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts index ef9ad0507cc5..f23f495a5deb 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts +++ b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts @@ -41,7 +41,7 @@ import Suite from './Suite'; import Timer from './Timer'; const create = function(createOptions: Object): $J { - const j$: $J = {...createOptions}; + const j$ = {...createOptions} as $J; j$._DEFAULT_TIMEOUT_INTERVAL = 5000; diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 984d5cab77a9..b0bb4bfb7eac 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -77,7 +77,11 @@ function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { // Similar to promisifyLifeCycleFunction but throws an error // when the return value is neither a Promise nor `undefined` -function promisifyIt(originalFn: Function, env: $J['Env'], jasmine: Jasmine) { +function promisifyIt( + originalFn: Function, + env: $J['currentEnv_'], + jasmine: Jasmine, +) { return function(specName: string, fn: Function, timeout?: number) { if (!fn) { const spec = originalFn.call(env, specName); @@ -135,7 +139,7 @@ function promisifyIt(originalFn: Function, env: $J['Env'], jasmine: Jasmine) { function makeConcurrent( originalFn: Function, - env: $J['Env'], + env: $J['currentEnv_'], mutex: ReturnType, ) { return function(specName: string, fn: () => Promise, timeout: number) { diff --git a/packages/jest-jasmine2/src/pTimeout.ts b/packages/jest-jasmine2/src/pTimeout.ts index b4edafc439a4..dfe96c134e8c 100644 --- a/packages/jest-jasmine2/src/pTimeout.ts +++ b/packages/jest-jasmine2/src/pTimeout.ts @@ -10,8 +10,8 @@ export default function pTimeout( promise: Promise, ms: number, - clearTimeout: (timeoutID: number) => void, - setTimeout: (func: () => void, delay: number) => number, + clearTimeout: NodeJS.Global['clearTimeout'], + setTimeout: NodeJS.Global['setTimeout'], onTimeout: () => any, ): Promise { return new Promise((resolve, reject) => { diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index 6ff21325d025..ac5a73efe4e6 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -11,7 +11,7 @@ import pTimeout from './pTimeout'; type Global = NodeJS.Global; export type Options = { - clearTimeout: (timeoutID: number) => void | Global['clearTimeout']; + clearTimeout: Global['clearTimeout']; fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array; diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index fba2d87d77c4..a1b3588a4047 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -51,9 +51,9 @@ export type Jasmine = { export interface $J extends NodeJS.Global { _DEFAULT_TIMEOUT_INTERVAL: number; currentEnv_: ReturnType['prototype']; - getEnv: (options: object) => ReturnType; + getEnv: (options: object) => ReturnType['prototype']; createSpy: typeof createSpy; - Env: ReturnType['prototype']; + Env: ReturnType; JsApiReporter: typeof JsApiReporter; ReportDispatcher: typeof ReportDispatcher; Spec: typeof Spec; @@ -64,12 +64,11 @@ export interface $J extends NodeJS.Global { testPath: Config.Path; } +interface Global { + jasmine: Jasmine; +} + declare global { - /* namespace jest { - interface Global { - jasmine: Jasmine; - } - }*/ module NodeJS { interface Global { jasmine: Jasmine; From bc6d48f3e0daab943a64cc843bf5f739b0bcecad Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sat, 2 Mar 2019 16:39:55 +0500 Subject: [PATCH 10/25] Small tweaks --- packages/jest-jasmine2/package.json | 1 + packages/jest-jasmine2/src/PCancelable.ts | 2 +- .../src/assertionErrorMessage.ts | 1 - packages/jest-jasmine2/src/each.ts | 5 +-- packages/jest-jasmine2/src/errorOnPrivate.ts | 2 +- packages/jest-jasmine2/src/index.ts | 12 +++--- .../jest-jasmine2/src/jasmine/CallTracker.ts | 10 ++--- packages/jest-jasmine2/src/jasmine/Env.ts | 39 ++++++++++++------- .../src/jasmine/JsApiReporter.ts | 10 ++--- .../src/jasmine/ReportDispatcher.ts | 2 +- packages/jest-jasmine2/src/jasmine/Spec.ts | 14 +++++-- .../jest-jasmine2/src/jasmine/SpyStrategy.ts | 2 +- packages/jest-jasmine2/src/jasmine/Suite.ts | 22 +++++------ .../jest-jasmine2/src/jasmine/createSpy.ts | 4 +- .../jest-jasmine2/src/jasmine/jasmineLight.ts | 14 +++---- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 15 ++++--- packages/jest-jasmine2/src/jestExpect.ts | 5 +-- packages/jest-jasmine2/src/queueRunner.ts | 2 +- .../jest-jasmine2/src/setup_jest_globals.ts | 5 ++- packages/jest-jasmine2/src/types.ts | 22 ++++++----- packages/jest-jasmine2/tsconfig.json | 3 +- packages/jest-types/src/Global.ts | 7 ---- packages/jest-types/src/TestResult.ts | 1 + .../src/convertDescriptorToString.ts | 6 +-- 24 files changed, 110 insertions(+), 96 deletions(-) diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index f555c88fb0d2..0942933a0bdb 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -11,6 +11,7 @@ "types": "build/index.d.ts", "dependencies": { "@babel/traverse": "^7.1.0", + "@jest/environment": "^24.1.0", "@jest/types": "^24.1.0", "chalk": "^2.0.1", "co": "^4.6.0", diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index 34f109313d20..45d74859aba3 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -25,7 +25,7 @@ class PCancelable extends Promise { static CancelError: CancelError; - static fn any>(fn: F) { + static fn) => any>(fn: F) { return function(...args: Parameters) { return new PCancelable>((onCancel, resolve, reject) => { args.unshift(onCancel); diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index be67c2d8bdcc..0be736d8ab97 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -12,7 +12,6 @@ import {AssertionErrorWithStack} from './types'; // TODO replace with import {DiffOptions} from 'jest-matcher-utils'; type DiffOptions = Parameters[2]; - const assertOperatorsMap: {[key: string]: string} = { '!=': 'notEqual', '!==': 'notStrictEqual', diff --git a/packages/jest-jasmine2/src/each.ts b/packages/jest-jasmine2/src/each.ts index 33a54a831552..cb489db03436 100644 --- a/packages/jest-jasmine2/src/each.ts +++ b/packages/jest-jasmine2/src/each.ts @@ -5,11 +5,10 @@ * LICENSE file in the root directory of this source tree. */ -import {Environment} from '@jest/types'; -// @ts-ignore TODO Remove ignore when jest-each is migrated to TS +import {Environment} from '@jest/environment'; import {bind as bindEach} from 'jest-each'; -export default (environment: Environment.Environment): void => { +export default (environment: Environment): void => { environment.global.it.each = bindEach(environment.global.it); environment.global.fit.each = bindEach(environment.global.fit); environment.global.xit.each = bindEach(environment.global.xit); diff --git a/packages/jest-jasmine2/src/errorOnPrivate.ts b/packages/jest-jasmine2/src/errorOnPrivate.ts index 9d2469252269..045b8528e5db 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.ts +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -49,7 +49,7 @@ export function installErrorOnPrivate(global: Global.Global): void { } const original = jasmine.DEFAULT_TIMEOUT_INTERVAL; - // $FlowFixMe Flow seems to be confused about accessors and tries to enfoce having a `value` property. + Object.defineProperty(jasmine, 'DEFAULT_TIMEOUT_INTERVAL', { configurable: true, enumerable: true, diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index c3eb5344b5bb..2cc341e20273 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -6,9 +6,9 @@ */ import path from 'path'; -import {Environment, Config, TestResult} from '@jest/types'; +import {Config, TestResult} from '@jest/types'; +import {Environment} from '@jest/enviroment'; import {SnapshotState} from 'jest-snapshot'; -// @ts-ignore TODO Remove ignore when jest-runtime is migrated to TS import Runtime from 'jest-runtime'; import {getCallsite} from 'jest-util'; @@ -23,7 +23,7 @@ const JASMINE = require.resolve('./jasmine/jasmineLight.ts'); async function jasmine2( globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, - environment: Environment.Environment, + environment: Environment, runtime: Runtime, testPath: string, ): Promise { @@ -43,7 +43,7 @@ async function jasmine2( // in a future version if (config.testLocationInResults === true) { const originalIt = environment.global.it; - environment.global.it = (...args: any[]) => { + environment.global.it = (...args: Array) => { const stack = getCallsite(1, runtime.getSourceMaps()); const it = originalIt(...args); @@ -53,7 +53,7 @@ async function jasmine2( }; const originalXit = environment.global.xit; - environment.global.xit = (...args: any[]) => { + environment.global.xit = (...args: Array) => { const stack = getCallsite(1, runtime.getSourceMaps()); const xit = originalXit(...args); @@ -63,7 +63,7 @@ async function jasmine2( }; const originalFit = environment.global.fit; - environment.global.fit = (...args: any[]) => { + environment.global.fit = (...args: Array) => { const stack = getCallsite(1, runtime.getSourceMaps()); const fit = originalFit(...args); diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.ts b/packages/jest-jasmine2/src/jasmine/CallTracker.ts index 2d680edbdedd..02a0b767ffdf 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.ts +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -31,7 +31,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export type Context = { object: unknown; - args: unknown[]; + args: Array; returnValue?: unknown; }; @@ -39,15 +39,15 @@ class CallTracker { track: (context: Context) => void; any: () => boolean; count: () => number; - argsFor: (index: number) => unknown[]; - all: () => Context[]; - allArgs: () => unknown[]; + argsFor: (index: number) => Array; + all: () => Array; + allArgs: () => Array; first: () => Context; mostRecent: () => Context; reset: () => void; constructor() { - let calls: Context[] = []; + let calls: Array = []; this.track = function(context: Context) { calls.push(context); diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index c05462f43989..61469f62da65 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -39,11 +39,11 @@ import queueRunner, { import treeProcessor from '../treeProcessor'; import isError from '../isError'; import assertionErrorMessage from '../assertionErrorMessage'; -import {$J, AssertionErrorWithStack, Reporter} from "../types"; +import {Jasmine, AssertionErrorWithStack, Reporter} from '../types'; import Spec, {SpecResult} from './Spec'; import Suite from './Suite'; -export default function(j$: $J) { +export default function(j$: Jasmine) { class Env { specFilter: (spec: Spec) => boolean; catchExceptions: (value: unknown) => boolean; @@ -58,9 +58,16 @@ export default function(j$: $J) { randomizeTests: (value: unknown) => void; randomTests: () => boolean; seed: (value: unknown) => unknown; - execute: (runnablesToRun: string[], suiteTree?: Suite) => Promise; + execute: ( + runnablesToRun: Array, + suiteTree?: Suite, + ) => Promise; fdescribe: (description: string, specDefinitions: Function) => Suite; - spyOn: () => any; + spyOn: ( + obj: {[key: string]: any}, + methodName: string, + accessType?: keyof PropertyDescriptor, + ) => any; beforeEach: ( beforeEachFunction: QueueableFn['fn'], timeout?: number, @@ -70,7 +77,7 @@ export default function(j$: $J) { addReporter: (reporterToAdd: Reporter) => void; it: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec; xdescribe: (description: string, specDefinitions: Function) => Suite; - xit: () => any; + xit: (description: string, fn: QueueableFn['fn'], timeout?: number) => any; beforeAll: (beforeAllFunction: Function, timeout?: number) => void; todo: () => Spec; provideFallbackReporter: (reporterToAdd: Reporter) => void; @@ -86,13 +93,14 @@ export default function(j$: $J) { const realClearTimeout = global.clearTimeout; const runnableResources: {[key: string]: {spies: []}} = {}; - const currentlyExecutingSuites: Suite[] = []; + const currentlyExecutingSuites: Array = []; let currentSpec: Spec | null = null; let throwOnExpectationFailure = false; let random = false; let seed: unknown | null = null; const topSuite = new j$.Suite({ id: getNextSuiteId(), + description: '', getTestPath() { return j$.testPath; }, @@ -146,8 +154,8 @@ export default function(j$: $J) { const beforeAndAfterFns = function(suite: Suite) { return function() { - let afters: QueueableFn[] = []; - let befores: QueueableFn[] = []; + let afters: Array = []; + let befores: Array = []; while (suite) { befores = befores.concat(suite.beforeFns); @@ -227,8 +235,8 @@ export default function(j$: $J) { } }; - let oldListenersException: NodeJS.UncaughtExceptionListener[]; - let oldListenersRejection: NodeJS.UnhandledRejectionListener[]; + let oldListenersException: Array; + let oldListenersRejection: Array; const executionSetup = function() { // Need to ensure we are the only ones handling these exceptions. oldListenersException = process.listeners('uncaughtException').slice(); @@ -385,7 +393,7 @@ export default function(j$: $J) { return suite; }; - const focusedRunnables: string[] = []; + const focusedRunnables: Array = []; this.fdescribe = function(description, specDefinitions) { const suite = suiteFactory(description); @@ -444,10 +452,10 @@ export default function(j$: $J) { const specFactory = ( description: string, - fn: Function, + fn: QueueableFn['fn'], suite: Suite, timeout?: number, - ) => { + ): Spec => { totalSpecsDefined++; const spec = new j$.Spec({ id: getNextSpecId(), @@ -534,7 +542,7 @@ export default function(j$: $J) { return spec; }; - this.xit = function(...args: any[]) { + this.xit = function(...args) { const spec = this.it.apply(this, args); spec.pend('Temporarily disabled with xit'); return spec; @@ -629,7 +637,7 @@ export default function(j$: $J) { checkIsError = check.isError; message = check.message; } - const errorAsErrorObject = checkIsError ? error : new Error(message); + const errorAsErrorObject = checkIsError ? error : new Error(message!); const runnable = currentRunnable(); if (!runnable) { @@ -640,6 +648,7 @@ export default function(j$: $J) { throw errorAsErrorObject; } + // @ts-ignore runnable.addExpectationResult(false, { matcherName: '', passed: false, diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index 6b5f15f96e6a..462820111503 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -51,12 +51,12 @@ export default class JsApiReporter { suiteStarted: (result: Suite) => void; suiteDone: (result: Suite) => void; - suiteResults: (index: number, length: number) => Suite[]; + suiteResults: (index: number, length: number) => Array; suites: () => {[key: string]: Suite}; - specResults: (index: number, length: number) => SpecResult[]; + specResults: (index: number, length: number) => Array; specDone: (result: SpecResult) => void; - specs: () => SpecResult[]; + specs: () => Array; constructor(options: {timer?: Timer}) { const timer = options.timer || noopTimer; @@ -92,7 +92,7 @@ export default class JsApiReporter { return status; }; - const suites: Suite[] = []; + const suites: Array = []; const suites_hash: {[key: string]: Suite} = {}; this.suiteStarted = function(result: Suite) { @@ -116,7 +116,7 @@ export default class JsApiReporter { return suites_hash; }; - const specs: SpecResult[] = []; + const specs: Array = []; this.specDone = function(result) { specs.push(result); diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index 1f74eedd9126..b223c418a2fa 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -48,7 +48,7 @@ export default class ReportDispatcher { })(method); } - let reporters: Reporter[] = []; + let reporters: Array = []; let fallbackReporter: Reporter | null = null; this.addReporter = function(reporter) { diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index 8c0690007258..d43566dadb02 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -48,7 +48,10 @@ export type Attributes = { throwOnExpectationFailure: unknown; getTestPath: () => Config.Path; queueableFn: QueueableFn; - beforeAndAfterFns: () => {befores: QueueableFn[]; afters: QueueableFn[]}; + beforeAndAfterFns: () => { + befores: Array; + afters: Array; + }; userContext: () => unknown; onStart: (context: Spec) => void; getSpecName: (spec: Spec) => string; @@ -62,7 +65,7 @@ export type SpecResult = { duration?: TestResult.Milliseconds; failedExpectations: Array; testPath: Config.Path; - passedExpectations: ReturnType[]; + passedExpectations: Array>; pendingReason: string; status: TestResult.Status; __callsite?: { @@ -76,7 +79,10 @@ export default class Spec { description: string; resultCallback: (result: SpecResult) => void; queueableFn: QueueableFn; - beforeAndAfterFns: () => {befores: QueueableFn[]; afters: QueueableFn[]}; + beforeAndAfterFns: () => { + befores: Array; + afters: Array; + }; userContext: () => unknown; onStart: (spec: Spec) => void; getSpecName: (spec: Spec) => string; @@ -242,7 +248,7 @@ export default class Spec { this.disabled = true; } - pend(message: string) { + pend(message?: string) { this.markedPending = true; if (message) { this.result.pendingReason = message; diff --git a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts index d86703aee41d..59c2faf24c05 100644 --- a/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts +++ b/packages/jest-jasmine2/src/jasmine/SpyStrategy.ts @@ -31,7 +31,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export default class SpyStrategy { identity: () => string; - exec: (...args: any[]) => unknown; + exec: (...args: Array) => unknown; callThrough: () => unknown; returnValue: (value: unknown) => unknown; returnValues: () => unknown; diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index cb3354878806..2de0b7cc5ccc 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -52,12 +52,12 @@ export default class Suite { parentSuite?: Suite; description: string; throwOnExpectationFailure: boolean; - beforeFns: QueueableFn[]; - afterFns: QueueableFn[]; - beforeAllFns: QueueableFn[]; - afterAllFns: QueueableFn[]; + beforeFns: Array; + afterFns: Array; + beforeAllFns: Array; + afterAllFns: Array; disabled: boolean; - children: Suite[]; + children: Array; result: SuiteResult; sharedContext?: object; markedPending: boolean = false; @@ -67,7 +67,7 @@ export default class Suite { constructor(attrs: { id: string; parentSuite?: Suite; - description?: string; + description: string; throwOnExpectationFailure?: boolean; getTestPath: () => Config.Path; }) { @@ -124,7 +124,7 @@ export default class Suite { this.afterAllFns.unshift(fn); } - addChild(child: Suite) { + addChild(child: Suite | Suite) { this.children.push(child); } @@ -191,7 +191,7 @@ export default class Suite { } } - addExpectationResult(...args: ExpectationResultFactoryOptions[]) { + addExpectationResult(...args: Array) { if (isAfterAll(this.children) && isFailure(args)) { const data = args[1]; this.result.failedExpectations.push(expectationResultFactory(data)); @@ -210,13 +210,13 @@ export default class Suite { } } - execute(..._args: any[]) {} + execute(..._args: Array) {} } -function isAfterAll(children: Suite[]) { +function isAfterAll(children: Array) { return children && children[0] && children[0].result.status; } -function isFailure(args: unknown[]) { +function isFailure(args: Array) { return !args[0]; } diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index f4a8b704f078..183e0263fbf3 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -34,7 +34,7 @@ import CallTracker, {Context} from './CallTracker'; import SpyStrategy from './SpyStrategy'; interface Spy extends Record { - (...args: any[]): unknown; + (...args: Array): unknown; and: SpyStrategy; calls: CallTracker; } @@ -48,7 +48,7 @@ function createSpy(name: string, originalFn: Function): Spy { }, }); const callTracker = new CallTracker(); - const spy = function(this: {[key: string]: any}, ...args: any[]) { + const spy = function(this: {[key: string]: any}, ...args: Array) { const callData: Context = { object: this, args: Array.prototype.slice.apply(arguments), diff --git a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts index f23f495a5deb..8890fe5d94d9 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts +++ b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts @@ -30,7 +30,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ -import {Jasmine, $J} from '../types'; +import {Jasmine} from '../types'; import createSpy from './createSpy'; import Env from './Env'; import JsApiReporter from './JsApiReporter'; @@ -40,12 +40,12 @@ import SpyRegistry from './spyRegistry'; import Suite from './Suite'; import Timer from './Timer'; -const create = function(createOptions: Object): $J { - const j$ = {...createOptions} as $J; +const create = function(createOptions: Object): Jasmine { + const j$ = {...createOptions} as Jasmine; j$._DEFAULT_TIMEOUT_INTERVAL = 5000; - j$.getEnv = function(options: object) { + j$.getEnv = function(options?: object) { const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; @@ -63,8 +63,7 @@ const create = function(createOptions: Object): $J { return j$; }; -// Interface is a reserved word in strict mode, so can't export it as ESM -const interface = function(jasmine: Jasmine, env: any) { +const _interface = function(jasmine: Jasmine, env: any) { const jasmineInterface = { describe(description: string, specDefinitions: Function) { return env.describe(description, specDefinitions); @@ -148,4 +147,5 @@ const interface = function(jasmine: Jasmine, env: any) { return jasmineInterface; }; -export = {create, interface}; +// Interface is a reserved word in strict mode, so can't export it as ESM +export = {create, interface: _interface}; diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index b0bb4bfb7eac..626be7ef9101 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -15,7 +15,7 @@ import co from 'co'; import isGeneratorFn from 'is-generator-fn'; import throat from 'throat'; import isError from './isError'; -import {$J, Jasmine} from './types'; +import {Jasmine} from './types'; import Spec from './jasmine/Spec'; interface DoneFn { @@ -27,9 +27,12 @@ function isPromise(obj: any) { return obj && typeof obj.then === 'function'; } -function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { - return function( - fn: () => Promise | GeneratorFunction | undefined, +function promisifyLifeCycleFunction( + originalFn: Function, + env: Jasmine['currentEnv_'], +) { + return function( + fn: () => Promise | GeneratorFunction | undefined, timeout: number, ) { if (!fn) { @@ -79,7 +82,7 @@ function promisifyLifeCycleFunction(originalFn: Function, env: $J['Env']) { // when the return value is neither a Promise nor `undefined` function promisifyIt( originalFn: Function, - env: $J['currentEnv_'], + env: Jasmine['currentEnv_'], jasmine: Jasmine, ) { return function(specName: string, fn: Function, timeout?: number) { @@ -139,7 +142,7 @@ function promisifyIt( function makeConcurrent( originalFn: Function, - env: $J['currentEnv_'], + env: Jasmine['currentEnv_'], mutex: ReturnType, ) { return function(specName: string, fn: () => Promise, timeout: number) { diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index 57810c84d833..2c48fc043b17 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -47,7 +47,7 @@ export default (config: {expand: boolean}) => { Object.keys(jasmineMatchersObject).forEach(name => { jestMatchersObject[name] = function( this: Matchers.MatcherState, - ...args: unknown[] + ...args: Array ): RawMatcherFn { // use "expect.extend" if you need to use equality testers (via this.equal) const result = jasmineMatchersObject[name](null, null); @@ -60,8 +60,7 @@ export default (config: {expand: boolean}) => { // @ts-ignore args, ) - : // @ts-ignore - result.compare.apply( + : result.compare.apply( null, // @ts-ignore args, diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index ac5a73efe4e6..994704ace0b7 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -20,7 +20,7 @@ export type Options = { }; export type QueueableFn = { - fn: (next: (...args: any[]) => void) => void; + fn: (done: (error?: any) => void) => void; timeout?: () => number; initError?: Error; }; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 6a08eafba972..508daa67a4e5 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -5,7 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -import {PrettyFormat, Config} from '@jest/types'; +import {Config} from '@jest/types'; +import {Plugin} from 'pretty-format'; import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import { buildSnapshotResolver, @@ -17,7 +18,7 @@ import JasmineSpec, {Attributes, SpecResult} from './jasmine/Spec'; export type SetupOptions = { config: Config.ProjectConfig; globalConfig: Config.GlobalConfig; - localRequire: (moduleName: string) => PrettyFormat.Plugin; + localRequire: (moduleName: string) => Plugin; testPath: Config.Path; }; diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index a1b3588a4047..7c40abf26ad3 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -42,16 +42,12 @@ export type RawMatcherFn = ( // -------END------- export type Reporter = JsApiReporter | Jasmine2Reporter; -export type Jasmine = { - Spec: typeof Spec; - JsApiReporter: typeof JsApiReporter; - Timer: typeof Timer; -} & typeof expect; -export interface $J extends NodeJS.Global { +export type Jasmine = { _DEFAULT_TIMEOUT_INTERVAL: number; + DEFAULT_TIMEOUT_INTERVAL: number; currentEnv_: ReturnType['prototype']; - getEnv: (options: object) => ReturnType['prototype']; + getEnv: (options?: object) => ReturnType['prototype']; createSpy: typeof createSpy; Env: ReturnType; JsApiReporter: typeof JsApiReporter; @@ -62,10 +58,16 @@ export interface $J extends NodeJS.Global { Timer: typeof Timer; version: string; testPath: Config.Path; -} + addMatchers: Function; +} & typeof expect & + NodeJS.Global; -interface Global { - jasmine: Jasmine; +declare module '@jest/types' { + namespace Global { + interface Global { + jasmine: Jasmine; + } + } } declare global { diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json index ac1c17ec8821..6f488bb4df6e 100644 --- a/packages/jest-jasmine2/tsconfig.json +++ b/packages/jest-jasmine2/tsconfig.json @@ -12,6 +12,7 @@ {"path": "../jest-snapshot"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, - {"path": "../jest-diff"} + {"path": "../jest-diff"}, + {"path": "../jest-runtime"} ] } diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index 2a2db149db20..ea212881fdcd 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -13,9 +13,6 @@ export type TestFn = (done?: DoneFn) => Promise | void | undefined; export type BlockFn = () => void; export type BlockName = string; -// TODO: Get rid of this at some point -type JasmineType = {_DEFAULT_TIMEOUT_INTERVAL?: number; addMatchers: Function}; - export type Col = unknown; export type Row = Array; export type Table = Array; @@ -77,13 +74,9 @@ export interface Global extends NodeJS.Global { xdescribe: DescribeBase; fdescribe: DescribeBase; __coverage__: CoverageMapData; - jasmine: JasmineType; } declare global { - namespace jest { - interface _Global extends Global {} - } module NodeJS { interface Global { it: It; diff --git a/packages/jest-types/src/TestResult.ts b/packages/jest-types/src/TestResult.ts index 022add832094..589b2951b7d9 100644 --- a/packages/jest-types/src/TestResult.ts +++ b/packages/jest-types/src/TestResult.ts @@ -20,6 +20,7 @@ export type FailedAssertion = { message?: string; actual?: any; pass?: boolean; + passed?: boolean; expected?: any; isNot?: boolean; stack?: string; diff --git a/packages/jest-util/src/convertDescriptorToString.ts b/packages/jest-util/src/convertDescriptorToString.ts index 53141efd0682..50324d218204 100644 --- a/packages/jest-util/src/convertDescriptorToString.ts +++ b/packages/jest-util/src/convertDescriptorToString.ts @@ -6,9 +6,9 @@ */ // See: https://github.com/facebook/jest/pull/5154 -export default function convertDescriptorToString( - descriptor: string | Function, -): string | undefined { +export default function convertDescriptorToString< + T extends number | string | Function | undefined +>(descriptor: T): T | string { if ( typeof descriptor === 'string' || typeof descriptor === 'number' || From d2b3eba848b86edab1b7e0e40b462bf676052fe5 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sat, 2 Mar 2019 17:23:18 +0500 Subject: [PATCH 11/25] Small tweaks --- packages/jest-jasmine2/src/each.ts | 4 ++-- packages/jest-jasmine2/src/jasmine/Env.ts | 8 ++++---- packages/jest-jasmine2/src/jasmine/createSpy.ts | 7 +------ packages/jest-jasmine2/src/jasmine/spyRegistry.ts | 6 +++--- packages/jest-jasmine2/src/jasmineAsyncInstall.ts | 2 +- packages/jest-jasmine2/src/types.ts | 9 +++++++++ packages/jest-types/src/Global.ts | 3 +++ 7 files changed, 23 insertions(+), 16 deletions(-) diff --git a/packages/jest-jasmine2/src/each.ts b/packages/jest-jasmine2/src/each.ts index cb489db03436..05bc252304a6 100644 --- a/packages/jest-jasmine2/src/each.ts +++ b/packages/jest-jasmine2/src/each.ts @@ -5,10 +5,10 @@ * LICENSE file in the root directory of this source tree. */ -import {Environment} from '@jest/environment'; +import {JestEnvironment} from '@jest/environment'; import {bind as bindEach} from 'jest-each'; -export default (environment: Environment): void => { +export default (environment: JestEnvironment): void => { environment.global.it.each = bindEach(environment.global.it); environment.global.fit.each = bindEach(environment.global.fit); environment.global.xit.each = bindEach(environment.global.xit); diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 61469f62da65..9363d26bfe2f 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -39,7 +39,7 @@ import queueRunner, { import treeProcessor from '../treeProcessor'; import isError from '../isError'; import assertionErrorMessage from '../assertionErrorMessage'; -import {Jasmine, AssertionErrorWithStack, Reporter} from '../types'; +import {Jasmine, AssertionErrorWithStack, Reporter, Spy} from '../types'; import Spec, {SpecResult} from './Spec'; import Suite from './Suite'; @@ -67,7 +67,7 @@ export default function(j$: Jasmine) { obj: {[key: string]: any}, methodName: string, accessType?: keyof PropertyDescriptor, - ) => any; + ) => Spy; beforeEach: ( beforeEachFunction: QueueableFn['fn'], timeout?: number, @@ -343,8 +343,8 @@ export default function(j$: Jasmine) { spyRegistry.allowRespy(allow); }; - this.spyOn = function() { - return spyRegistry.spyOn.apply(spyRegistry, arguments); + this.spyOn = function(...args) { + return spyRegistry.spyOn.apply(spyRegistry, args); }; const suiteFactory = function(description: string) { diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index 183e0263fbf3..2b80cb1f0eae 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -30,15 +30,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ +import {Spy} from '../types'; import CallTracker, {Context} from './CallTracker'; import SpyStrategy from './SpyStrategy'; -interface Spy extends Record { - (...args: Array): unknown; - and: SpyStrategy; - calls: CallTracker; -} - function createSpy(name: string, originalFn: Function): Spy { const spyStrategy = new SpyStrategy({ name, diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts index 874b65d4fdb3..3eec7aa548a9 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -29,8 +29,8 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import {Spy} from '../types'; import CallTracker from './CallTracker'; - import createSpy from './createSpy'; import SpyStrategy from './SpyStrategy'; @@ -57,7 +57,7 @@ export default class SpyRegistry { obj: {[key: string]: any}, methodName: string, accessType?: keyof PropertyDescriptor, - ) => unknown; + ) => Spy; clearSpies: () => void; respy: unknown; @@ -65,7 +65,7 @@ export default class SpyRegistry { obj: {[key: string]: any}, propertyName: string, accessType: keyof PropertyDescriptor, - ) => unknown; + ) => Spy; constructor({ currentSpies = () => [], diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 626be7ef9101..5db63dafb8eb 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -32,7 +32,7 @@ function promisifyLifeCycleFunction( env: Jasmine['currentEnv_'], ) { return function( - fn: () => Promise | GeneratorFunction | undefined, + fn: Function | (() => Promise) | GeneratorFunction | undefined, timeout: number, ) { if (!fn) { diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index 7c40abf26ad3..2a87280d6cba 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -17,6 +17,8 @@ import createSpy from './jasmine/createSpy'; import ReportDispatcher from './jasmine/ReportDispatcher'; import SpyRegistry from './jasmine/spyRegistry'; import Suite from './jasmine/Suite'; +import SpyStrategy from './jasmine/SpyStrategy'; +import CallTracker from './jasmine/CallTracker'; export interface AssertionErrorWithStack extends AssertionError { stack: string; @@ -43,6 +45,12 @@ export type RawMatcherFn = ( export type Reporter = JsApiReporter | Jasmine2Reporter; +export interface Spy extends Record { + (...args: Array): unknown; + and: SpyStrategy; + calls: CallTracker; +} + export type Jasmine = { _DEFAULT_TIMEOUT_INTERVAL: number; DEFAULT_TIMEOUT_INTERVAL: number; @@ -66,6 +74,7 @@ declare module '@jest/types' { namespace Global { interface Global { jasmine: Jasmine; + [key: string]: any; } } } diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index ea212881fdcd..049ff270e366 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -24,6 +24,9 @@ export type EachTestFn = ( ...args: Array ) => Promise | void | undefined; +// TODO: Get rid of this at some point +type Jasmine = {_DEFAULT_TIMEOUT_INTERVAL?: number; addMatchers: Function}; + type Each = ( table: EachTable, ...taggedTemplateData: Array From b52c8f2a065fca9980415c83171cc892ab082fe9 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sat, 2 Mar 2019 19:38:55 +0500 Subject: [PATCH 12/25] TS migration part (6) --- packages/jest-jasmine2/src/errorOnPrivate.ts | 3 ++- packages/jest-jasmine2/src/index.ts | 12 ++++++++--- .../jest-jasmine2/src/jasmine/createSpy.ts | 9 ++++++-- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 2 +- packages/jest-jasmine2/src/jestExpect.ts | 4 ++-- .../jest-jasmine2/src/setup_jest_globals.ts | 5 +++-- packages/jest-jasmine2/src/types.ts | 21 +++---------------- packages/jest-jasmine2/tsconfig.json | 3 ++- packages/jest-types/src/Global.ts | 2 ++ 9 files changed, 31 insertions(+), 30 deletions(-) diff --git a/packages/jest-jasmine2/src/errorOnPrivate.ts b/packages/jest-jasmine2/src/errorOnPrivate.ts index 045b8528e5db..02eed6b809dd 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.ts +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -7,6 +7,7 @@ import {Global} from '@jest/types'; import {ErrorWithStack} from 'jest-util'; +import {Jasmine} from './types'; // prettier-ignore const disabledGlobals: {[key: string]: string} = { @@ -28,7 +29,7 @@ const disabledJasmineMethods: {[key: string]: string} = { }; export function installErrorOnPrivate(global: Global.Global): void { - const {jasmine} = global; + const jasmine = global.jasmine as Jasmine; Object.keys(disabledGlobals).forEach(functionName => { global[functionName] = () => { throwAtFunction(disabledGlobals[functionName], global[functionName]); diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 2cc341e20273..f386f9b8d71c 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -7,7 +7,7 @@ import path from 'path'; import {Config, TestResult} from '@jest/types'; -import {Environment} from '@jest/enviroment'; +import {JestEnvironment} from '@jest/environment'; import {SnapshotState} from 'jest-snapshot'; import Runtime from 'jest-runtime'; @@ -17,13 +17,14 @@ import {installErrorOnPrivate} from './errorOnPrivate'; import JasmineReporter from './reporter'; import jasmineAsyncInstall from './jasmineAsyncInstall'; import Spec from './jasmine/Spec'; +import {Jasmine as JestJasmine} from './types'; const JASMINE = require.resolve('./jasmine/jasmineLight.ts'); async function jasmine2( globalConfig: Config.GlobalConfig, - config: Config.ProjectConfig, - environment: Environment, + config: Config.JestEnviroment, + environment: JestEnvironment, runtime: Runtime, testPath: string, ): Promise { @@ -204,4 +205,9 @@ const addSnapshotData = ( return results; }; +// eslint-disable-next-line +namespace jasmine2 { + export type Jasmine = JestJasmine; +} + export = jasmine2; diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index 2b80cb1f0eae..97be40b1c55c 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -34,7 +34,12 @@ import {Spy} from '../types'; import CallTracker, {Context} from './CallTracker'; import SpyStrategy from './SpyStrategy'; -function createSpy(name: string, originalFn: Function): Spy { +interface Fn { + (): any; + [key: string]: any; +} + +function createSpy(name: string, originalFn: Fn): Spy { const spyStrategy = new SpyStrategy({ name, fn: originalFn, @@ -43,7 +48,7 @@ function createSpy(name: string, originalFn: Function): Spy { }, }); const callTracker = new CallTracker(); - const spy = function(this: {[key: string]: any}, ...args: Array) { + const spy: Spy = function(...args) { const callData: Context = { object: this, args: Array.prototype.slice.apply(arguments), diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 5db63dafb8eb..78301d995634 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -176,7 +176,7 @@ export default function jasmineAsyncInstall( globalConfig: Config.GlobalConfig, global: Global.Global, ) { - const jasmine = global.jasmine; + const jasmine = global.jasmine as Jasmine; const mutex = throat(globalConfig.maxConcurrency); const env = jasmine.getEnv(); diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index 2c48fc043b17..65a2fb5fc021 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -14,7 +14,7 @@ import { toThrowErrorMatchingSnapshot, toThrowErrorMatchingInlineSnapshot, } from 'jest-snapshot'; -import {RawMatcherFn} from './types'; +import {RawMatcherFn, Jasmine} from './types'; type JasmineMatcher = { (matchersUtil: any, context: any): JasmineMatcher; @@ -35,7 +35,7 @@ export default (config: {expand: boolean}) => { }); expect.addSnapshotSerializer = addSerializer; - const jasmine = global.jasmine; + const jasmine = global.jasmine as Jasmine; jasmine.anything = expect.anything; jasmine.any = expect.any; jasmine.objectContaining = expect.objectContaining; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 508daa67a4e5..cff86b27cb45 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -14,6 +14,7 @@ import { addSerializer, } from 'jest-snapshot'; import JasmineSpec, {Attributes, SpecResult} from './jasmine/Spec'; +import {Jasmine} from './types'; export type SetupOptions = { config: Config.ProjectConfig; @@ -59,7 +60,7 @@ const addAssertionErrors = (result: SpecResult) => { }; const patchJasmine = () => { - global.jasmine.Spec = (realSpec => { + (global.jasmine as Jasmine).Spec = (realSpec => { class Spec extends realSpec { constructor(attr: Attributes) { const resultCallback = attr.resultCallback; @@ -78,7 +79,7 @@ const patchJasmine = () => { } return Spec; - })(global.jasmine.Spec); + })((global.jasmine as Jasmine).Spec); }; export default ({ diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index 2a87280d6cba..3ffb98c67473 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -7,6 +7,7 @@ import {AssertionError} from 'assert'; import {Config} from '@jest/types'; + import expect from 'expect'; import Spec from './jasmine/Spec'; import JsApiReporter from './jasmine/JsApiReporter'; @@ -46,9 +47,10 @@ export type RawMatcherFn = ( export type Reporter = JsApiReporter | Jasmine2Reporter; export interface Spy extends Record { - (...args: Array): unknown; + (this: {[key: string]: any}, ...args: Array): unknown; and: SpyStrategy; calls: CallTracker; + [key: string]: any; } export type Jasmine = { @@ -69,20 +71,3 @@ export type Jasmine = { addMatchers: Function; } & typeof expect & NodeJS.Global; - -declare module '@jest/types' { - namespace Global { - interface Global { - jasmine: Jasmine; - [key: string]: any; - } - } -} - -declare global { - module NodeJS { - interface Global { - jasmine: Jasmine; - } - } -} diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json index 6f488bb4df6e..f77e16cb0a4e 100644 --- a/packages/jest-jasmine2/tsconfig.json +++ b/packages/jest-jasmine2/tsconfig.json @@ -13,6 +13,7 @@ {"path": "../jest-util"}, {"path": "../pretty-format"}, {"path": "../jest-diff"}, - {"path": "../jest-runtime"} + {"path": "../jest-runtime"}, + {"path": "../jest-environment"} ] } diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index 049ff270e366..4dc35ac5e89b 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -77,6 +77,7 @@ export interface Global extends NodeJS.Global { xdescribe: DescribeBase; fdescribe: DescribeBase; __coverage__: CoverageMapData; + jasmine: Jasmine; } declare global { @@ -90,6 +91,7 @@ declare global { describe: Describe; xdescribe: DescribeBase; fdescribe: DescribeBase; + jasmine: Jasmine; } } } From a3263b576d108929d3ee1b3cbe448f0d92f8f3f9 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 15:21:58 +0500 Subject: [PATCH 13/25] TS migration part (final) --- packages/jest-jasmine2/src/errorOnPrivate.ts | 20 ++++++++--- .../src/expectationResultFactory.ts | 2 +- packages/jest-jasmine2/src/index.ts | 23 +++++++------ packages/jest-jasmine2/src/jasmine/Env.ts | 11 +++--- .../src/jasmine/JsApiReporter.ts | 34 +++++++++++-------- .../src/jasmine/ReportDispatcher.ts | 25 +++++++++++--- packages/jest-jasmine2/src/jasmine/Suite.ts | 17 +++++----- .../jest-jasmine2/src/jasmine/spyRegistry.ts | 8 ++--- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 19 +++++++---- packages/jest-jasmine2/src/reporter.ts | 33 ++++++++++-------- packages/jest-jasmine2/src/treeProcessor.ts | 11 +++++- packages/jest-jasmine2/src/types.ts | 28 ++++++++++++--- packages/jest-types/src/Global.ts | 12 ++++--- 13 files changed, 159 insertions(+), 84 deletions(-) diff --git a/packages/jest-jasmine2/src/errorOnPrivate.ts b/packages/jest-jasmine2/src/errorOnPrivate.ts index 02eed6b809dd..1bef83eadea5 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.ts +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -9,16 +9,25 @@ import {Global} from '@jest/types'; import {ErrorWithStack} from 'jest-util'; import {Jasmine} from './types'; +type DisabledGlobalKeys = 'fail' | 'pending' | 'spyOn' | 'spyOnProperty'; // prettier-ignore -const disabledGlobals: {[key: string]: string} = { +const disabledGlobals: {[K in DisabledGlobalKeys]: string} = { fail: 'Illegal usage of global `fail`, prefer throwing an error, or the `done.fail` callback.', pending: 'Illegal usage of global `pending`, prefer explicitly skipping a test using `test.skip`', spyOn: 'Illegal usage of global `spyOn`, prefer `jest.spyOn`.', spyOnProperty: 'Illegal usage of global `spyOnProperty`, prefer `jest.spyOn`.', }; +type DisabledJasmineMethodsKeys = + | 'addMatchers' + | 'any' + | 'anything' + | 'arrayContaining' + | 'createSpy' + | 'objectContaining' + | 'stringMatching'; // prettier-ignore -const disabledJasmineMethods: {[key: string]: string} = { +const disabledJasmineMethods: {[key in DisabledJasmineMethodsKeys]: string} = { addMatchers: 'Illegal usage of `jasmine.addMatchers`, prefer `expect.extends`.', any: 'Illegal usage of `jasmine.any`, prefer `expect.any`.', anything: 'Illegal usage of `jasmine.anything`, prefer `expect.anything`.', @@ -30,13 +39,16 @@ const disabledJasmineMethods: {[key: string]: string} = { export function installErrorOnPrivate(global: Global.Global): void { const jasmine = global.jasmine as Jasmine; - Object.keys(disabledGlobals).forEach(functionName => { + + Object.keys(disabledGlobals).forEach(key => { + const functionName = key as DisabledGlobalKeys; global[functionName] = () => { throwAtFunction(disabledGlobals[functionName], global[functionName]); }; }); - Object.keys(disabledJasmineMethods).forEach(methodName => { + Object.keys(disabledJasmineMethods).forEach(key => { + const methodName = key as DisabledJasmineMethodsKeys; jasmine[methodName] = () => { throwAtFunction(disabledJasmineMethods[methodName], jasmine[methodName]); }; diff --git a/packages/jest-jasmine2/src/expectationResultFactory.ts b/packages/jest-jasmine2/src/expectationResultFactory.ts index 52959c082256..e18b59a15b97 100644 --- a/packages/jest-jasmine2/src/expectationResultFactory.ts +++ b/packages/jest-jasmine2/src/expectationResultFactory.ts @@ -62,7 +62,7 @@ export type Options = { actual?: any; error?: any; expected?: any; - message?: string; + message?: string | null; }; export default function expectationResultFactory( diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index f386f9b8d71c..a837995a5969 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import {Config, TestResult} from '@jest/types'; +import { Config, Global, TestResult } from "@jest/types"; import {JestEnvironment} from '@jest/environment'; import {SnapshotState} from 'jest-snapshot'; import Runtime from 'jest-runtime'; @@ -23,7 +23,7 @@ const JASMINE = require.resolve('./jasmine/jasmineLight.ts'); async function jasmine2( globalConfig: Config.GlobalConfig, - config: Config.JestEnviroment, + config: Config.ProjectConfig, environment: JestEnvironment, runtime: Runtime, testPath: string, @@ -44,34 +44,37 @@ async function jasmine2( // in a future version if (config.testLocationInResults === true) { const originalIt = environment.global.it; - environment.global.it = (...args: Array) => { + environment.global.it = ((...args) => { const stack = getCallsite(1, runtime.getSourceMaps()); const it = originalIt(...args); + // @ts-ignore it.result.__callsite = stack; return it; - }; + }) as Global.Global['it']; const originalXit = environment.global.xit; - environment.global.xit = (...args: Array) => { + environment.global.xit = ((...args) => { const stack = getCallsite(1, runtime.getSourceMaps()); const xit = originalXit(...args); + // @ts-ignore xit.result.__callsite = stack; return xit; - }; + }) as Global.Global['xit']; const originalFit = environment.global.fit; - environment.global.fit = (...args: Array) => { + environment.global.fit = ((...args) => { const stack = getCallsite(1, runtime.getSourceMaps()); const fit = originalFit(...args); + // @ts-ignore fit.result.__callsite = stack; return fit; - }; + }) as Global.Global['fit']; } jasmineAsyncInstall(globalConfig, environment.global); @@ -87,7 +90,7 @@ async function jasmine2( environment.global.describe.only = environment.global.fdescribe; if (config.timers === 'fake') { - environment.fakeTimers.useFakeTimers(); + environment.fakeTimers!.useFakeTimers(); } env.beforeEach(() => { @@ -103,7 +106,7 @@ async function jasmine2( runtime.resetAllMocks(); if (config.timers === 'fake') { - environment.fakeTimers.useFakeTimers(); + environment.fakeTimers!.useFakeTimers(); } } diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 9363d26bfe2f..7de03f45f515 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -36,7 +36,7 @@ import queueRunner, { Options as QueueRunnerOptions, QueueableFn, } from '../queueRunner'; -import treeProcessor from '../treeProcessor'; +import treeProcessor, {TreeNode} from '../treeProcessor'; import isError from '../isError'; import assertionErrorMessage from '../assertionErrorMessage'; import {Jasmine, AssertionErrorWithStack, Reporter, Spy} from '../types'; @@ -78,7 +78,7 @@ export default function(j$: Jasmine) { it: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec; xdescribe: (description: string, specDefinitions: Function) => Suite; xit: (description: string, fn: QueueableFn['fn'], timeout?: number) => any; - beforeAll: (beforeAllFunction: Function, timeout?: number) => void; + beforeAll: (beforeAllFunction: QueueableFn['fn'], timeout?: number) => void; todo: () => Spec; provideFallbackReporter: (reporterToAdd: Reporter) => void; allowRespy: (allow: boolean) => void; @@ -92,7 +92,7 @@ export default function(j$: Jasmine) { const realSetTimeout = global.setTimeout; const realClearTimeout = global.clearTimeout; - const runnableResources: {[key: string]: {spies: []}} = {}; + const runnableResources: {[key: string]: {spies: Array}} = {}; const currentlyExecutingSuites: Array = []; let currentSpec: Spec | null = null; let throwOnExpectationFailure = false; @@ -293,7 +293,7 @@ export default function(j$: Jasmine) { } }, nodeStart(suite) { - currentlyExecutingSuites.push(suite); + currentlyExecutingSuites.push(suite as Suite); defaultResourcesForRunnable( suite.id, suite.parentSuite && suite.parentSuite.id, @@ -306,7 +306,7 @@ export default function(j$: Jasmine) { }, queueRunnerFactory, runnableIds: runnablesToRun, - tree: suiteTree, + tree: suiteTree as TreeNode, }); currentDeclarationSuite = lastDeclarationSuite; @@ -648,7 +648,6 @@ export default function(j$: Jasmine) { throw errorAsErrorObject; } - // @ts-ignore runnable.addExpectationResult(false, { matcherName: '', passed: false, diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index 462820111503..7a9740354d6d 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -30,8 +30,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ import {SpecResult} from './Spec'; -import Suite from './Suite'; +import {SuiteResult} from "./Suite"; import Timer from './Timer'; +import {Reporter, RunDetails} from '../types'; const noopTimer = { start() {}, @@ -40,23 +41,24 @@ const noopTimer = { }, }; -export default class JsApiReporter { +export default class JsApiReporter implements Reporter { started: boolean; finished: boolean; - runDetails: unknown; - jasmineStarted: () => void; - jasmineDone: (runDetails: SpecResult) => void; + runDetails: RunDetails; + jasmineStarted: (runDetails: RunDetails) => void; + jasmineDone: (runDetails: RunDetails) => void; status: () => unknown; executionTime: () => unknown; - suiteStarted: (result: Suite) => void; - suiteDone: (result: Suite) => void; - suiteResults: (index: number, length: number) => Array; - suites: () => {[key: string]: Suite}; + suiteStarted: (result: SuiteResult) => void; + suiteDone: (result: SuiteResult) => void; + suiteResults: (index: number, length: number) => Array; + suites: () => {[key: string]: SuiteResult}; specResults: (index: number, length: number) => Array; specDone: (result: SpecResult) => void; specs: () => Array; + specStarted: (spec: SpecResult) => void; constructor(options: {timer?: Timer}) { const timer = options.timer || noopTimer; @@ -74,7 +76,7 @@ export default class JsApiReporter { let executionTime: number; - function validateAfterAllExceptions({failedExpectations}: SpecResult) { + function validateAfterAllExceptions({failedExpectations}: RunDetails) { if (failedExpectations && failedExpectations.length > 0) { throw failedExpectations[0]; } @@ -92,14 +94,16 @@ export default class JsApiReporter { return status; }; - const suites: Array = []; - const suites_hash: {[key: string]: Suite} = {}; + const suites: Array = []; + const suites_hash: {[key: string]: SuiteResult} = {}; - this.suiteStarted = function(result: Suite) { + this.specStarted = function() {}; + + this.suiteStarted = function(result: SuiteResult) { suites_hash[result.id] = result; }; - this.suiteDone = function(result: Suite) { + this.suiteDone = function(result: SuiteResult) { storeSuite(result); }; @@ -107,7 +111,7 @@ export default class JsApiReporter { return suites.slice(index, index + length); }; - function storeSuite(result: Suite) { + function storeSuite(result: SuiteResult) { suites.push(result); suites_hash[result.id] = result; } diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index b223c418a2fa..dab52c999020 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -28,15 +28,29 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import {Reporter} from '../types'; +import {Reporter, RunDetails} from '../types'; +import {SpecResult} from './Spec'; +import {SuiteResult} from './Suite'; -export default class ReportDispatcher { +export default class ReportDispatcher implements Reporter { addReporter: (reporter: Reporter) => void; provideFallbackReporter: (reporter: Reporter) => void; clearReporters: () => void; - [key: string]: any; - constructor(methods: Array) { + // @ts-ignore + jasmineDone: (runDetails: RunDetails) => void; + // @ts-ignore + jasmineStarted: (runDetails: RunDetails) => void; + // @ts-ignore + specDone: (result: SpecResult) => void; + // @ts-ignore + specStarted: (spec: SpecResult) => void; + // @ts-ignore + suiteDone: (result: SuiteResult) => void; + // @ts-ignore + suiteStarted: (result: SuiteResult) => void; + + constructor(methods: Array) { const dispatchedMethods = methods || []; for (let i = 0; i < dispatchedMethods.length; i++) { @@ -65,13 +79,14 @@ export default class ReportDispatcher { return this; - function dispatch(method: string, args: any) { + function dispatch(method: keyof Reporter, args: any) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } for (let i = 0; i < reporters.length; i++) { const reporter = reporters[i]; if (reporter[method]) { + // @ts-ignore reporter[method].apply(reporter, args); } } diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 2de0b7cc5ccc..2d33728c516c 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -33,12 +33,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import {convertDescriptorToString} from 'jest-util'; import {Config} from '@jest/types'; import ExpectationFailed from '../ExpectationFailed'; -import expectationResultFactory, { - Options as ExpectationResultFactoryOptions, -} from '../expectationResultFactory'; +import expectationResultFactory from '../expectationResultFactory'; import {QueueableFn} from '../queueRunner'; +import Spec from './Spec'; -type SuiteResult = { +export type SuiteResult = { id: string; description: string; fullName: string; @@ -57,7 +56,7 @@ export default class Suite { beforeAllFns: Array; afterAllFns: Array; disabled: boolean; - children: Array; + children: Array; result: SuiteResult; sharedContext?: object; markedPending: boolean = false; @@ -124,7 +123,7 @@ export default class Suite { this.afterAllFns.unshift(fn); } - addChild(child: Suite | Suite) { + addChild(child: Suite | Spec) { this.children.push(child); } @@ -169,7 +168,7 @@ export default class Suite { return this.sharedUserContext(); } - onException(...args: Array) { + onException(...args: Parameters) { if (args[0] instanceof ExpectationFailed) { return; } @@ -191,7 +190,7 @@ export default class Suite { } } - addExpectationResult(...args: Array) { + addExpectationResult(...args: Parameters) { if (isAfterAll(this.children) && isFailure(args)) { const data = args[1]; this.result.failedExpectations.push(expectationResultFactory(data)); @@ -213,7 +212,7 @@ export default class Suite { execute(..._args: Array) {} } -function isAfterAll(children: Array) { +function isAfterAll(children: Array) { return children && children[0] && children[0].result.status; } diff --git a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts index 3eec7aa548a9..6e05820e8206 100644 --- a/packages/jest-jasmine2/src/jasmine/spyRegistry.ts +++ b/packages/jest-jasmine2/src/jasmine/spyRegistry.ts @@ -70,7 +70,7 @@ export default class SpyRegistry { constructor({ currentSpies = () => [], }: { - currentSpies?: () => Array<{restoreObjectToOriginalState: () => void}>; + currentSpies?: () => Array; } = {}) { this.allowRespy = function(allow) { this.respy = allow; @@ -140,7 +140,7 @@ export default class SpyRegistry { currentSpies().push({ restoreObjectToOriginalState: restoreStrategy, - }); + } as Spy); obj[methodName] = spiedMethod; @@ -214,7 +214,7 @@ export default class SpyRegistry { currentSpies().push({ restoreObjectToOriginalState: restoreStrategy, - }); + } as Spy); const spiedDescriptor = {...descriptor, [accessType]: spiedProperty}; @@ -227,7 +227,7 @@ export default class SpyRegistry { const spies = currentSpies(); for (let i = spies.length - 1; i >= 0; i--) { const spyEntry = spies[i]; - spyEntry.restoreObjectToOriginalState(); + spyEntry.restoreObjectToOriginalState!(); } }; } diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 78301d995634..cbcb31576f64 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -33,7 +33,7 @@ function promisifyLifeCycleFunction( ) { return function( fn: Function | (() => Promise) | GeneratorFunction | undefined, - timeout: number, + timeout?: number, ) { if (!fn) { return originalFn.call(env); @@ -144,8 +144,8 @@ function makeConcurrent( originalFn: Function, env: Jasmine['currentEnv_'], mutex: ReturnType, -) { - return function(specName: string, fn: () => Promise, timeout: number) { +): Global.ItConcurrentBase { + return function(specName, fn, timeout) { if ( env != null && !env.specFilter({getFullName: () => specName || ''} as Spec) @@ -182,9 +182,16 @@ export default function jasmineAsyncInstall( const env = jasmine.getEnv(); env.it = promisifyIt(env.it, env, jasmine); env.fit = promisifyIt(env.fit, env, jasmine); - global.it.concurrent = makeConcurrent(env.it, env, mutex); - global.it.concurrent.only = makeConcurrent(env.fit, env, mutex); - global.it.concurrent.skip = makeConcurrent(env.xit, env, mutex); + global.it.concurrent = (env => { + const concurrent = makeConcurrent( + env.it, + env, + mutex, + ) as Global.ItConcurrentExtended; + concurrent.only = makeConcurrent(env.fit, env, mutex); + concurrent.skip = makeConcurrent(env.xit, env, mutex); + return concurrent; + })(env); global.fit.concurrent = makeConcurrent(env.fit, env, mutex); env.afterAll = promisifyLifeCycleFunction(env.afterAll, env); env.afterEach = promisifyLifeCycleFunction(env.afterEach, env); diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 6bebec3ae75c..d956ae5966b7 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -7,20 +7,21 @@ import {Config, TestResult} from '@jest/types'; import {formatResultsErrors} from 'jest-message-util'; -import Spec, {SpecResult} from './jasmine/Spec'; -import Suite from './jasmine/Suite'; +import {SpecResult} from './jasmine/Spec'; +import {SuiteResult} from './jasmine/Suite'; +import {Reporter, RunDetails} from './types'; type Microseconds = number; -export default class Jasmine2Reporter { - _testResults: Array; - _globalConfig: Config.GlobalConfig; - _config: Config.ProjectConfig; - _currentSuites: Array; - _resolve: any; - _resultsPromise: Promise; - _startTimes: Map; - _testPath: Config.Path; +export default class Jasmine2Reporter implements Reporter { + private _testResults: Array; + private _globalConfig: Config.GlobalConfig; + private _config: Config.ProjectConfig; + private _currentSuites: Array; + private _resolve: any; + private _resultsPromise: Promise; + private _startTimes: Map; + private _testPath: Config.Path; constructor( globalConfig: Config.GlobalConfig, @@ -37,7 +38,9 @@ export default class Jasmine2Reporter { this._startTimes = new Map(); } - specStarted(spec: Spec) { + jasmineStarted(_runDetails: RunDetails) {} + + specStarted(spec: SpecResult) { this._startTimes.set(spec.id, Date.now()); } @@ -47,15 +50,15 @@ export default class Jasmine2Reporter { ); } - suiteStarted(suite: Suite): void { + suiteStarted(suite: SuiteResult): void { this._currentSuites.push(suite.description); } - suiteDone(): void { + suiteDone(_result: SuiteResult): void { this._currentSuites.pop(); } - jasmineDone(): void { + jasmineDone(_runDetails: RunDetails): void { let numFailingTests = 0; let numPassingTests = 0; let numPendingTests = 0; diff --git a/packages/jest-jasmine2/src/treeProcessor.ts b/packages/jest-jasmine2/src/treeProcessor.ts index 106a2c73666e..db59f94b0b11 100644 --- a/packages/jest-jasmine2/src/treeProcessor.ts +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -14,7 +14,16 @@ type Options = { tree: TreeNode; }; -type TreeNode = Suite; +export type TreeNode = { + afterAllFns: Array; + beforeAllFns: Array; + disabled?: boolean; + execute: (onComplete: () => void, enabled: boolean) => void; + id: string; + onException: (error: Error) => void; + sharedUserContext: () => any; + children?: Array; +} & Pick; export default function treeProcessor(options: Options) { const { diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index 3ffb98c67473..f4c6be31a852 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -9,15 +9,14 @@ import {AssertionError} from 'assert'; import {Config} from '@jest/types'; import expect from 'expect'; -import Spec from './jasmine/Spec'; +import Spec, {SpecResult} from './jasmine/Spec'; import JsApiReporter from './jasmine/JsApiReporter'; -import Jasmine2Reporter from './reporter'; import Timer from './jasmine/Timer'; import Env from './jasmine/Env'; import createSpy from './jasmine/createSpy'; import ReportDispatcher from './jasmine/ReportDispatcher'; import SpyRegistry from './jasmine/spyRegistry'; -import Suite from './jasmine/Suite'; +import Suite, {SuiteResult} from './jasmine/Suite'; import SpyStrategy from './jasmine/SpyStrategy'; import CallTracker from './jasmine/CallTracker'; @@ -44,12 +43,25 @@ export type RawMatcherFn = ( ) => ExpectationResult; // -------END------- -export type Reporter = JsApiReporter | Jasmine2Reporter; +export type RunDetails = { + totalSpecsDefined?: number; + failedExpectations?: SuiteResult['failedExpectations']; +}; + +export type Reporter = { + jasmineDone: (runDetails: RunDetails) => void; + jasmineStarted: (runDetails: RunDetails) => void; + specDone: (result: SpecResult) => void; + specStarted: (spec: SpecResult) => void; + suiteDone: (result: SuiteResult) => void; + suiteStarted: (result: SuiteResult) => void; +}; export interface Spy extends Record { (this: {[key: string]: any}, ...args: Array): unknown; and: SpyStrategy; calls: CallTracker; + restoreObjectToOriginalState?: () => void; [key: string]: any; } @@ -71,3 +83,11 @@ export type Jasmine = { addMatchers: Function; } & typeof expect & NodeJS.Global; + +declare global { + module NodeJS { + interface Global { + expect: typeof expect; + } + } +} diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index 4dc35ac5e89b..d237eaa3ef5d 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -62,15 +62,15 @@ export interface DescribeBase { } export interface Describe extends DescribeBase { - only: ItBase; - skip: ItBase; + only: DescribeBase; + skip: DescribeBase; } // TODO: Maybe add `| Window` in the future? export interface Global extends NodeJS.Global { - it: It; + it: ItConcurrent; test: ItConcurrent; - fit: ItBase; + fit: ItBase & {concurrent?: ItConcurrentBase}; xit: ItBase; xtest: ItBase; describe: Describe; @@ -78,6 +78,10 @@ export interface Global extends NodeJS.Global { fdescribe: DescribeBase; __coverage__: CoverageMapData; jasmine: Jasmine; + fail: () => void; + pending: () => void; + spyOn: () => void; + spyOnProperty: () => void; } declare global { From d5a4c17ee4f98c17a53296ef492bc14bb14e3ef4 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 15:28:39 +0500 Subject: [PATCH 14/25] Linter fixes --- packages/jest-jasmine2/src/index.ts | 2 +- packages/jest-jasmine2/src/jasmine/JsApiReporter.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index a837995a5969..0855daa9170f 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { Config, Global, TestResult } from "@jest/types"; +import {Config, Global, TestResult} from '@jest/types'; import {JestEnvironment} from '@jest/environment'; import {SnapshotState} from 'jest-snapshot'; import Runtime from 'jest-runtime'; diff --git a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts index 7a9740354d6d..8a726f7aa6f7 100644 --- a/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts +++ b/packages/jest-jasmine2/src/jasmine/JsApiReporter.ts @@ -29,10 +29,10 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* eslint-disable sort-keys */ +import {Reporter, RunDetails} from '../types'; import {SpecResult} from './Spec'; -import {SuiteResult} from "./Suite"; +import {SuiteResult} from './Suite'; import Timer from './Timer'; -import {Reporter, RunDetails} from '../types'; const noopTimer = { start() {}, From b73f4b7f332993f7159d96be4e371c6dd0695336 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 17:00:33 +0500 Subject: [PATCH 15/25] Fix tests --- packages/jest-jasmine2/src/PCancelable.ts | 13 ++++----- .../jest-jasmine2/src/__tests__/Suite.test.ts | 5 ++-- .../src/__tests__/queueRunner.test.ts | 6 ++++ .../src/__tests__/reporter.test.ts | 22 +++++++++----- packages/jest-jasmine2/src/index.ts | 2 +- packages/jest-jasmine2/src/jasmine/Env.ts | 29 ++++++++++--------- packages/jest-jasmine2/src/jasmine/Suite.ts | 16 +++++----- 7 files changed, 54 insertions(+), 39 deletions(-) diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index 45d74859aba3..4e93de6b291b 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -14,8 +14,7 @@ class CancelError extends Error { } } -// @ts-ignore -class PCancelable extends Promise { +class PCancelable { private _pending: boolean; private _canceled: boolean; private _cancel?: Function; @@ -34,13 +33,11 @@ class PCancelable extends Promise { }; } - // @ts-ignore - constructor(executor: (onCancel, resolve, reject) => any) { - // @ts-ignore + constructor( + executor: (onCancel: Function, resolve: Function, reject: Function) => any, + ) { this._pending = true; - // @ts-ignore this._canceled = false; - // @ts-ignore this._promise = new Promise((resolve, reject) => { this._reject = reject; @@ -90,4 +87,6 @@ class PCancelable extends Promise { } } +Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + export = PCancelable; diff --git a/packages/jest-jasmine2/src/__tests__/Suite.test.ts b/packages/jest-jasmine2/src/__tests__/Suite.test.ts index 1c4350454901..e8323ea2e589 100644 --- a/packages/jest-jasmine2/src/__tests__/Suite.test.ts +++ b/packages/jest-jasmine2/src/__tests__/Suite.test.ts @@ -6,7 +6,7 @@ * */ -import Suite from '../jasmine/Suite'; +import Suite, {Attributes} from '../jasmine/Suite'; describe('Suite', () => { let suite: Suite; @@ -14,11 +14,12 @@ describe('Suite', () => { beforeEach(() => { suite = new Suite({ getTestPath: () => '', - }); + } as Attributes); }); it("doesn't throw on addExpectationResult when there are no children", () => { expect(() => { + // @ts-ignore suite.addExpectationResult(); }).not.toThrow(); }); diff --git a/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts index f76defe15fdf..d98fe7fcfe3d 100644 --- a/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts +++ b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts @@ -26,6 +26,7 @@ describe('queueRunner', () => { ], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(fnTwo).toHaveBeenCalled(); @@ -49,6 +50,7 @@ describe('queueRunner', () => { ], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(fail).toHaveBeenCalled(); @@ -77,6 +79,7 @@ describe('queueRunner', () => { ], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(onException).toHaveBeenCalledWith(error); @@ -104,6 +107,7 @@ describe('queueRunner', () => { ], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(onException).toHaveBeenCalled(); @@ -123,6 +127,7 @@ describe('queueRunner', () => { queueableFns: [{fn: failFn}], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(options.fail).toHaveBeenCalledWith('miserably', 'failed'); @@ -147,6 +152,7 @@ describe('queueRunner', () => { ], setTimeout, }; + // @ts-ignore await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(fail).toHaveBeenCalledWith(error); diff --git a/packages/jest-jasmine2/src/__tests__/reporter.test.ts b/packages/jest-jasmine2/src/__tests__/reporter.test.ts index aacdb9dca778..4e92f9b9cf4a 100644 --- a/packages/jest-jasmine2/src/__tests__/reporter.test.ts +++ b/packages/jest-jasmine2/src/__tests__/reporter.test.ts @@ -7,26 +7,32 @@ */ import JasmineReporter from '../reporter'; +import {SuiteResult} from '../jasmine/Suite'; +import {SpecResult} from '../jasmine/Spec'; describe('Jasmine2Reporter', () => { let reporter: JasmineReporter; beforeEach(() => { + // @ts-ignore reporter = new JasmineReporter({}); }); it('reports nested suites', () => { - const makeSpec = (name: string) => ({ - description: 'description', - failedExpectations: [], - fullName: name, - }); - reporter.suiteStarted({description: 'parent'}); - reporter.suiteStarted({description: 'child'}); + const makeSpec = (name: string) => + ({ + description: 'description', + failedExpectations: [], + fullName: name, + } as SpecResult); + reporter.suiteStarted({description: 'parent'} as SuiteResult); + reporter.suiteStarted({description: 'child'} as SuiteResult); reporter.specDone(makeSpec('spec 1')); + // @ts-ignore reporter.suiteDone(); - reporter.suiteStarted({description: 'child 2'}); + reporter.suiteStarted({description: 'child 2'} as SuiteResult); reporter.specDone(makeSpec('spec 2')); + // @ts-ignore reporter.jasmineDone(); return reporter.getResults().then(runResults => { diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 0855daa9170f..b4affb33c273 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -19,7 +19,7 @@ import jasmineAsyncInstall from './jasmineAsyncInstall'; import Spec from './jasmine/Spec'; import {Jasmine as JestJasmine} from './types'; -const JASMINE = require.resolve('./jasmine/jasmineLight.ts'); +const JASMINE = require.resolve('./jasmine/jasmineLight.js'); async function jasmine2( globalConfig: Config.GlobalConfig, diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 7de03f45f515..abfcc619e814 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -44,7 +44,7 @@ import Spec, {SpecResult} from './Spec'; import Suite from './Suite'; export default function(j$: Jasmine) { - class Env { + return class Env { specFilter: (spec: Spec) => boolean; catchExceptions: (value: unknown) => boolean; throwOnExpectationFailure: (value: unknown) => void; @@ -98,6 +98,17 @@ export default function(j$: Jasmine) { let throwOnExpectationFailure = false; let random = false; let seed: unknown | null = null; + let nextSpecId = 0; + let nextSuiteId = 0; + + const getNextSpecId = function() { + return 'spec' + nextSpecId++; + }; + + const getNextSuiteId = function() { + return 'suite' + nextSuiteId++; + }; + const topSuite = new j$.Suite({ id: getNextSuiteId(), description: '', @@ -128,16 +139,6 @@ export default function(j$: Jasmine) { return true; }; - let nextSpecId = 0; - const getNextSpecId = function() { - return 'spec' + nextSpecId++; - }; - - let nextSuiteId = 0; - function getNextSuiteId() { - return 'suite' + nextSuiteId++; - } - const defaultResourcesForRunnable = function( id: string, _parentRunnableId?: string, @@ -380,6 +381,7 @@ export default function(j$: Jasmine) { suite.pend(); } if (currentDeclarationSuite.markedTodo) { + // @ts-ignore TODO Possible error: Suite does not have todo method suite.todo(); } addSpecsToSuite(suite, specDefinitions); @@ -630,6 +632,7 @@ export default function(j$: Jasmine) { if (error instanceof AssertionError) { checkIsError = false; + // @ts-ignore TODO Possible error: j$.Spec does not have expand property message = assertionErrorMessage(error, {expand: j$.Spec.expand}); } else { const check = isError(error); @@ -658,7 +661,5 @@ export default function(j$: Jasmine) { }); }; } - } - - return Env; + }; } diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 2d33728c516c..3acce5b5f1d2 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -46,6 +46,14 @@ export type SuiteResult = { status?: string; }; +export type Attributes = { + id: string; + parentSuite?: Suite; + description: string; + throwOnExpectationFailure?: boolean; + getTestPath: () => Config.Path; +}; + export default class Suite { id: string; parentSuite?: Suite; @@ -63,13 +71,7 @@ export default class Suite { markedTodo: boolean = false; isFocused: boolean = false; - constructor(attrs: { - id: string; - parentSuite?: Suite; - description: string; - throwOnExpectationFailure?: boolean; - getTestPath: () => Config.Path; - }) { + constructor(attrs: Attributes) { this.id = attrs.id; this.parentSuite = attrs.parentSuite; this.description = convertDescriptorToString(attrs.description); From 69a427e646842291c875f15bbd350874f3884106 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 18:05:56 +0500 Subject: [PATCH 16/25] Small tweaks --- packages/jest-diff/src/index.ts | 5 +++ .../src/{PCancelable.ts => PCancelable.js} | 44 ++++++++----------- .../src/assertionErrorMessage.ts | 6 +-- packages/jest-jasmine2/src/index.ts | 8 ++-- packages/jest-jasmine2/src/queueRunner.ts | 3 +- packages/jest-jasmine2/tsconfig.json | 3 +- packages/jest-snapshot/src/index.ts | 1 + 7 files changed, 33 insertions(+), 37 deletions(-) rename packages/jest-jasmine2/src/{PCancelable.ts => PCancelable.js} (54%) diff --git a/packages/jest-diff/src/index.ts b/packages/jest-diff/src/index.ts index 176a8cbd5d38..5df5bd742f85 100644 --- a/packages/jest-diff/src/index.ts +++ b/packages/jest-diff/src/index.ts @@ -150,4 +150,9 @@ function compareObjects(a: Object, b: Object, options?: DiffOptions) { return diffMessage; } +/* eslint-disable-next-line no-redeclare */ +namespace diff { + export type DiffOptionsType = DiffOptions; +} + export = diff; diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.js similarity index 54% rename from packages/jest-jasmine2/src/PCancelable.ts rename to packages/jest-jasmine2/src/PCancelable.js index 4e93de6b291b..f5a488ec0efb 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.js @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -/* eslint-disable no-this-before-super, constructor-super */ +'use strict'; class CancelError extends Error { constructor() { @@ -14,42 +14,33 @@ class CancelError extends Error { } } -class PCancelable { - private _pending: boolean; - private _canceled: boolean; - private _cancel?: Function; - // @ts-ignore - private _reject: (reason?: any) => void; - private _promise: Promise; - - static CancelError: CancelError; - - static fn) => any>(fn: F) { - return function(...args: Parameters) { - return new PCancelable>((onCancel, resolve, reject) => { +class PCancelable { + static fn(fn) { + return function() { + const args = [].slice.apply(arguments); + return new PCancelable((onCancel, resolve, reject) => { args.unshift(onCancel); fn.apply(null, args).then(resolve, reject); }); }; } - constructor( - executor: (onCancel: Function, resolve: Function, reject: Function) => any, - ) { + constructor(executor) { this._pending = true; this._canceled = false; - this._promise = new Promise((resolve, reject) => { + + this._promise = new Promise((resolve, reject) => { this._reject = reject; return executor( - (fn: Function) => { + fn => { this._cancel = fn; }, - (val: T) => { + val => { this._pending = false; resolve(val); }, - (err?: any) => { + err => { this._pending = false; reject(err); }, @@ -57,12 +48,12 @@ class PCancelable { }); } - then(...args: Parameters['then']>) { - return this._promise.then.apply(this._promise, args); + then() { + return this._promise.then.apply(this._promise, arguments); } - catch(...args: Parameters['catch']>) { - return this._promise.catch.apply(this._promise, args); + catch() { + return this._promise.catch.apply(this._promise, arguments); } cancel() { @@ -89,4 +80,5 @@ class PCancelable { Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); -export = PCancelable; +module.exports = PCancelable; +module.exports.CancelError = CancelError; diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index 0be736d8ab97..f1beeebf63eb 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -6,12 +6,10 @@ */ import {diff, printReceived, printExpected} from 'jest-matcher-utils'; +import jestDiff from 'jest-diff'; import chalk from 'chalk'; import {AssertionErrorWithStack} from './types'; -// TODO replace with import {DiffOptions} from 'jest-matcher-utils'; -type DiffOptions = Parameters[2]; - const assertOperatorsMap: {[key: string]: string} = { '!=': 'notEqual', '!==': 'notStrictEqual', @@ -82,7 +80,7 @@ const assertMatcherHint = (operator: string | null, operatorName: string) => { function assertionErrorMessage( error: AssertionErrorWithStack, - options: DiffOptions, + options: jestDiff.DiffOptionsType, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index b4affb33c273..40d9c6015cdc 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -8,7 +8,7 @@ import path from 'path'; import {Config, Global, TestResult} from '@jest/types'; import {JestEnvironment} from '@jest/environment'; -import {SnapshotState} from 'jest-snapshot'; +import {SnapshotStateType} from 'jest-snapshot'; import Runtime from 'jest-runtime'; import {getCallsite} from 'jest-util'; @@ -139,8 +139,7 @@ async function jasmine2( }); } - // TODO: make just snapshotState: SnapshotState when `jest-snapshot` is ESM - const snapshotState: typeof SnapshotState.prototype = runtime + const snapshotState: SnapshotStateType = runtime .requireInternalModule(path.resolve(__dirname, './setup_jest_globals.js')) .default({ config, @@ -173,10 +172,9 @@ async function jasmine2( return addSnapshotData(results, snapshotState); } -// TODO: make just snapshotState: SnapshotState when `jest-snapshot` is ESM const addSnapshotData = ( results: TestResult.TestResult, - snapshotState: typeof SnapshotState.prototype, + snapshotState: SnapshotStateType, ) => { results.testResults.forEach( ({fullName, status}: TestResult.AssertionResult) => { diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index 994704ace0b7..f10f484c79a7 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +// @ts-ignore ignore vendor file import PCancelable from './PCancelable'; import pTimeout from './pTimeout'; @@ -26,7 +27,7 @@ export type QueueableFn = { }; export default function queueRunner(options: Options) { - const token = new PCancelable((onCancel, resolve) => { + const token = new PCancelable((onCancel: Function, resolve: Function) => { onCancel(resolve); }); diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json index f77e16cb0a4e..75ee60d51e3b 100644 --- a/packages/jest-jasmine2/tsconfig.json +++ b/packages/jest-jasmine2/tsconfig.json @@ -14,6 +14,7 @@ {"path": "../pretty-format"}, {"path": "../jest-diff"}, {"path": "../jest-runtime"}, - {"path": "../jest-environment"} + {"path": "../jest-environment"}, + {"path": "../jest-each"} ] } diff --git a/packages/jest-snapshot/src/index.ts b/packages/jest-snapshot/src/index.ts index 0ed61078506c..94cf5d63ff0f 100644 --- a/packages/jest-snapshot/src/index.ts +++ b/packages/jest-snapshot/src/index.ts @@ -314,6 +314,7 @@ const JestSnapshot = { /* eslint-disable-next-line no-redeclare */ namespace JestSnapshot { export type SnapshotResolver = JestSnapshotResolver; + export type SnapshotStateType = SnapshotState; } export = JestSnapshot; From 7aeeb6f5adaf46b234f64d950313db7943b08f26 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 18:14:22 +0500 Subject: [PATCH 17/25] Update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01505a96598d..08db1114a2fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ ### Chore & Maintenance +- `[jest-jasmine2]`: TS migration ([#7970](https://github.com/facebook/jest/pull/7970)) - `[jest-each]`: Refactor into multiple files with better types ([#8018](https://github.com/facebook/jest/pull/8018)) - `[jest-each]`: Migrate to Typescript ([#8007](https://github.com/facebook/jest/pull/8007)) - `[jest-environment-jsdom]`: Migrate to TypeScript ([#7985](https://github.com/facebook/jest/pull/8003)) From 26c59b533b26965dab171f0c5ace946593b95c35 Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 19:05:59 +0500 Subject: [PATCH 18/25] Tweaks for property fields --- packages/jest-jasmine2/src/jasmine/Spec.ts | 4 +++- packages/jest-jasmine2/src/jasmine/Suite.ts | 9 ++++++--- yarn.lock | 10 +--------- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index d43566dadb02..7a60ac484016 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -96,7 +96,7 @@ export default class Spec { markedPending?: boolean; expand?: boolean; - static pendingSpecExceptionMessage = '=> marked Pending'; + static pendingSpecExceptionMessage: string; static isPendingSpecException(e: Error) { return !!( @@ -293,6 +293,8 @@ export default class Spec { } } +Spec.pendingSpecExceptionMessage = '=> marked Pending'; + const extractCustomPendingMessage = function(e: Error) { const fullMessage = e.toString(); const boilerplateStart = fullMessage.indexOf( diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 3acce5b5f1d2..0d781b3053ca 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -67,11 +67,14 @@ export default class Suite { children: Array; result: SuiteResult; sharedContext?: object; - markedPending: boolean = false; - markedTodo: boolean = false; - isFocused: boolean = false; + markedPending: boolean; + markedTodo: boolean; + isFocused: boolean; constructor(attrs: Attributes) { + this.markedPending = false; + this.markedTodo = false; + this.isFocused = false; this.id = attrs.id; this.parentSuite = attrs.parentSuite; this.description = convertDescriptorToString(attrs.description); diff --git a/yarn.lock b/yarn.lock index d7670b5c202f..2a165b6d6a2f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1784,14 +1784,6 @@ "@types/prop-types" "*" csstype "^2.2.0" -"@types/readable-stream@^2.3.0": - version "2.3.1" - resolved "https://registry.yarnpkg.com/@types/readable-stream/-/readable-stream-2.3.1.tgz#59d458b51c84c585caea06e296e2225057c9ea8e" - integrity sha512-Dp6t95yGEOm2y669mQrSl0kUg+oL+bJEiCWMyDv0Yq+FcVvjzNRLTAqJks2LDBYYrazZXNI7lZXq3lp7MOvt4A== - dependencies: - "@types/node" "*" - safe-buffer "*" - "@types/resolve@*": version "0.0.8" resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-0.0.8.tgz#f26074d238e02659e323ce1a13d041eee280e194" @@ -11516,7 +11508,7 @@ rxjs@^6.4.0: dependencies: tslib "^1.9.0" -safe-buffer@*, safe-buffer@5.1.2, safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: +safe-buffer@5.1.2, safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== From 0625619dd83dd19f9fac5258a74c145a63fd6f4e Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 19:18:17 +0500 Subject: [PATCH 19/25] Resolve import/no-extraneous-dependencies --- packages/jest-jasmine2/package.json | 4 ++-- packages/jest-jasmine2/src/assertionErrorMessage.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index 0942933a0bdb..138f5b3b5a8a 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -20,6 +20,7 @@ "jest-each": "^24.0.0", "jest-matcher-utils": "^24.0.0", "jest-message-util": "^24.0.0", + "jest-runtime": "^24.1.0", "jest-snapshot": "^24.1.0", "jest-util": "^24.0.0", "pretty-format": "^24.0.0", @@ -27,8 +28,7 @@ }, "devDependencies": { "@types/babel__traverse": "^7.0.4", - "jest-diff": "^24.0.0", - "jest-runtime": "^24.1.0" + "jest-diff": "^24.0.0" }, "engines": { "node": ">= 6" diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index ef9c1a804e46..ea28f273c79b 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -6,7 +6,7 @@ */ import {diff, printReceived, printExpected} from 'jest-matcher-utils'; -import jestDiff from 'jest-diff'; +import jestDiff from 'jest-diff'; // eslint-disable-line import/no-extraneous-dependencies import chalk from 'chalk'; import {AssertionErrorWithStack} from './types'; From 14a15642319f4ee121bc01aedf8c39ac442720b4 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 3 Mar 2019 15:43:02 +0100 Subject: [PATCH 20/25] fix jest-diff import --- packages/jest-jasmine2/package.json | 3 +-- .../src/assertionErrorMessage.ts | 10 ++++++--- packages/jest-jasmine2/tsconfig.json | 21 +++++++++---------- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index 138f5b3b5a8a..ffca52f38b8b 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -27,8 +27,7 @@ "throat": "^4.0.0" }, "devDependencies": { - "@types/babel__traverse": "^7.0.4", - "jest-diff": "^24.0.0" + "@types/babel__traverse": "^7.0.4" }, "engines": { "node": ">= 6" diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index ea28f273c79b..3a5e6761ec84 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -5,8 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -import {diff, printReceived, printExpected} from 'jest-matcher-utils'; -import jestDiff from 'jest-diff'; // eslint-disable-line import/no-extraneous-dependencies +import { + diff, + printReceived, + printExpected, + DiffOptions, +} from 'jest-matcher-utils'; import chalk from 'chalk'; import {AssertionErrorWithStack} from './types'; @@ -80,7 +84,7 @@ const assertMatcherHint = (operator: string | null, operatorName: string) => { function assertionErrorMessage( error: AssertionErrorWithStack, - options: jestDiff.DiffOptions, + options: DiffOptions, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); diff --git a/packages/jest-jasmine2/tsconfig.json b/packages/jest-jasmine2/tsconfig.json index 75ee60d51e3b..4844e44aa790 100644 --- a/packages/jest-jasmine2/tsconfig.json +++ b/packages/jest-jasmine2/tsconfig.json @@ -5,16 +5,15 @@ "outDir": "build" }, "references": [ - {"path": "../jest-types"}, - {"path": "../expect"}, - {"path": "../jest-matcher-utils"}, - {"path": "../jest-message-util"}, - {"path": "../jest-snapshot"}, - {"path": "../jest-util"}, - {"path": "../pretty-format"}, - {"path": "../jest-diff"}, - {"path": "../jest-runtime"}, - {"path": "../jest-environment"}, - {"path": "../jest-each"} + {"path": "../expect"}, + {"path": "../jest-each"}, + {"path": "../jest-environment"}, + {"path": "../jest-matcher-utils"}, + {"path": "../jest-message-util"}, + {"path": "../jest-runtime"}, + {"path": "../jest-snapshot"}, + {"path": "../jest-types"}, + {"path": "../jest-util"}, + {"path": "../pretty-format"} ] } From 9a9c65fe45bf7912d0664b6845d65bc2549a48a6 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 3 Mar 2019 16:02:24 +0100 Subject: [PATCH 21/25] tweaks --- packages/jest-jasmine2/src/errorOnPrivate.ts | 24 ++++++++++++-------- packages/jest-jasmine2/src/index.ts | 4 ++-- packages/jest-jasmine2/src/reporter.ts | 4 ++-- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/jest-jasmine2/src/errorOnPrivate.ts b/packages/jest-jasmine2/src/errorOnPrivate.ts index 1bef83eadea5..afc0eb54eefc 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.ts +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -10,8 +10,9 @@ import {ErrorWithStack} from 'jest-util'; import {Jasmine} from './types'; type DisabledGlobalKeys = 'fail' | 'pending' | 'spyOn' | 'spyOnProperty'; + // prettier-ignore -const disabledGlobals: {[K in DisabledGlobalKeys]: string} = { +const disabledGlobals: Record = { fail: 'Illegal usage of global `fail`, prefer throwing an error, or the `done.fail` callback.', pending: 'Illegal usage of global `pending`, prefer explicitly skipping a test using `test.skip`', spyOn: 'Illegal usage of global `spyOn`, prefer `jest.spyOn`.', @@ -26,8 +27,9 @@ type DisabledJasmineMethodsKeys = | 'createSpy' | 'objectContaining' | 'stringMatching'; + // prettier-ignore -const disabledJasmineMethods: {[key in DisabledJasmineMethodsKeys]: string} = { +const disabledJasmineMethods: Record = { addMatchers: 'Illegal usage of `jasmine.addMatchers`, prefer `expect.extends`.', any: 'Illegal usage of `jasmine.any`, prefer `expect.any`.', anything: 'Illegal usage of `jasmine.anything`, prefer `expect.anything`.', @@ -40,15 +42,17 @@ const disabledJasmineMethods: {[key in DisabledJasmineMethodsKeys]: string} = { export function installErrorOnPrivate(global: Global.Global): void { const jasmine = global.jasmine as Jasmine; - Object.keys(disabledGlobals).forEach(key => { - const functionName = key as DisabledGlobalKeys; - global[functionName] = () => { - throwAtFunction(disabledGlobals[functionName], global[functionName]); - }; - }); + (Object.keys(disabledGlobals) as Array).forEach( + functionName => { + global[functionName] = () => { + throwAtFunction(disabledGlobals[functionName], global[functionName]); + }; + }, + ); - Object.keys(disabledJasmineMethods).forEach(key => { - const methodName = key as DisabledJasmineMethodsKeys; + (Object.keys(disabledJasmineMethods) as Array< + DisabledJasmineMethodsKeys + >).forEach(methodName => { jasmine[methodName] = () => { throwAtFunction(disabledJasmineMethods[methodName], jasmine[methodName]); }; diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 40d9c6015cdc..fc51347f0d79 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -19,7 +19,7 @@ import jasmineAsyncInstall from './jasmineAsyncInstall'; import Spec from './jasmine/Spec'; import {Jasmine as JestJasmine} from './types'; -const JASMINE = require.resolve('./jasmine/jasmineLight.js'); +const JASMINE = require.resolve('./jasmine/jasmineLight'); async function jasmine2( globalConfig: Config.GlobalConfig, @@ -206,7 +206,7 @@ const addSnapshotData = ( return results; }; -// eslint-disable-next-line +// eslint-disable-next-line no-redeclare namespace jasmine2 { export type Jasmine = JestJasmine; } diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index d956ae5966b7..c6f8c6743854 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -111,7 +111,7 @@ export default class Jasmine2Reporter implements Reporter { return this._resultsPromise; } - _addMissingMessageToStack(stack: string, message: string | undefined) { + private _addMissingMessageToStack(stack: string, message?: string) { // Some errors (e.g. Angular injection error) don't prepend error.message // to stack, instead the first line of the stack is just plain 'Error' const ERROR_REGEX = /^Error\s*\n/; @@ -126,7 +126,7 @@ export default class Jasmine2Reporter implements Reporter { return stack; } - _extractSpecResults( + private _extractSpecResults( specResult: SpecResult, ancestorTitles: Array, ): TestResult.AssertionResult { From f9106efaeb6948762a8be2f64ac67bd478e363fb Mon Sep 17 00:00:00 2001 From: doniyor2109 Date: Sun, 3 Mar 2019 20:04:15 +0500 Subject: [PATCH 22/25] Remove extra types --- packages/jest-jasmine2/src/index.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 40d9c6015cdc..decd81c9bf51 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -206,9 +206,4 @@ const addSnapshotData = ( return results; }; -// eslint-disable-next-line -namespace jasmine2 { - export type Jasmine = JestJasmine; -} - export = jasmine2; From 93f7414076790d4871dac176cb9fffc269b90494 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 4 Mar 2019 00:27:05 +0100 Subject: [PATCH 23/25] fix error after merging master --- packages/jest-jasmine2/src/jestExpect.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index 65a2fb5fc021..9453f1731638 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -5,8 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import {Matchers} from '@jest/types'; -import expect from 'expect'; +import expect, {MatcherState} from 'expect'; import { addSerializer, toMatchSnapshot, @@ -46,7 +45,7 @@ export default (config: {expand: boolean}) => { const jestMatchersObject = Object.create(null); Object.keys(jasmineMatchersObject).forEach(name => { jestMatchersObject[name] = function( - this: Matchers.MatcherState, + this: MatcherState, ...args: Array ): RawMatcherFn { // use "expect.extend" if you need to use equality testers (via this.equal) From 548f05f0c0dafd20df9b1df23e4837c2dd5d418c Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Tue, 5 Mar 2019 01:03:41 +0100 Subject: [PATCH 24/25] lint --- packages/jest-jasmine2/src/jasmine/jasmineLight.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts index 8890fe5d94d9..bde9103904fb 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmineLight.ts +++ b/packages/jest-jasmine2/src/jasmine/jasmineLight.ts @@ -40,7 +40,7 @@ import SpyRegistry from './spyRegistry'; import Suite from './Suite'; import Timer from './Timer'; -const create = function(createOptions: Object): Jasmine { +const create = function(createOptions: Record): Jasmine { const j$ = {...createOptions} as Jasmine; j$._DEFAULT_TIMEOUT_INTERVAL = 5000; @@ -133,7 +133,7 @@ const _interface = function(jasmine: Jasmine, env: any) { return env.fail.apply(env, arguments); }, - spyOn(obj: Object, methodName: string, accessType?: string) { + spyOn(obj: Record, methodName: string, accessType?: string) { return env.spyOn(obj, methodName, accessType); }, From 8e264a3d319fc2367dca8dfe904b542c8890c717 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Tue, 5 Mar 2019 01:12:36 +0100 Subject: [PATCH 25/25] fix type error --- packages/jest-jasmine2/src/jasmine/Env.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index abfcc619e814..365c72855fbb 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -226,7 +226,8 @@ export default function(j$: Jasmine) { return topSuite; }; - const uncaught = (err: Error) => { + const uncaught: NodeJS.UncaughtExceptionListener & + NodeJS.UnhandledRejectionListener = (err: any) => { if (currentSpec) { currentSpec.onException(err); currentSpec.cancel();