From 286dab2e577b5d043abe3dd92dac6287e4703744 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 3 Oct 2022 08:15:59 +0100 Subject: [PATCH] chore: fix some type errors in tests (#13360) --- docs/Configuration.md | 2 +- docs/Puppeteer.md | 2 +- e2e/global-setup-esm/__tests__/test.js | 4 +- e2e/global-setup-esm/setup.js | 6 +- e2e/global-teardown-esm/__tests__/test.js | 4 +- e2e/global-teardown-esm/teardown.js | 6 +- e2e/require-main/loader.js | 2 +- e2e/resolve-conditions/deno-env.js | 2 +- e2e/test-environment-async/TestEnvironment.js | 2 +- .../CircusAsyncHandleTestEventEnvironment.js | 2 +- .../CircusHandleTestEventEnvironment.js | 2 +- .../DocblockPragmasEnvironment.js | 2 +- e2e/test-environment/EsmDefaultEnvironment.js | 2 +- .../transform-environment/environment.ts | 9 +- examples/mongodb/mongo-environment.js | 12 +- examples/mongodb/setup.js | 4 +- examples/mongodb/teardown.js | 4 +- .../src/__tests__/isError.test.ts | 18 +- .../src/__tests__/assertionCounts.test.ts | 2 +- .../matchers-toEqual.property.test.ts | 2 +- .../matchers-toStrictEqual.property.test.ts | 6 +- .../expect/src/__tests__/matchers.test.js | 2 +- .../expect/src/__tests__/spyMatchers.test.ts | 1469 ++++++++--------- .../src/__tests__/toThrowMatchers.test.ts | 4 +- packages/jest-circus/README.md | 2 +- .../circusItFailingTestError.test.ts | 6 + .../__tests__/circusItTodoTestError.test.ts | 2 +- .../src/__tests__/hooksError.test.ts | 53 +- .../jest-cli/src/__tests__/cli/args.test.ts | 1 - .../jest-cli/src/init/__tests__/init.test.js | 2 +- .../src/__tests__/normalize.test.ts | 19 +- .../src/__tests__/readConfigs.test.ts | 2 +- packages/jest-config/src/normalize.ts | 2 +- .../src/__tests__/SearchSource.test.ts | 39 +- .../src/__tests__/collectHandles.test.js | 2 +- .../__tests__/getNoTestsFoundMessage.test.ts | 2 +- .../src/__tests__/watchFileChanges.test.ts | 8 +- packages/jest-diff/src/__tests__/diff.test.ts | 5 +- .../jest-each/src/__tests__/array.test.ts | 2 +- .../jest-each/src/__tests__/template.test.ts | 79 +- .../src/__tests__/legacyFakeTimers.test.ts | 22 +- .../src/__tests__/modernFakeTimers.test.ts | 19 +- .../src/__tests__/get_mock_name.test.js | 2 +- .../src/__tests__/includes_dotfiles.test.ts | 2 +- .../src/__tests__/index.test.js | 2 +- .../src/__tests__/worker.test.js | 2 +- .../src/lib/__tests__/fast_path.test.js | 2 +- .../src/watchers/WatchmanWatcher.js | 6 +- .../jest-jasmine2/src/__tests__/Suite.test.ts | 2 +- .../src/__tests__/hooksError.test.ts | 50 +- .../src/__tests__/itTestError.test.ts | 10 +- .../src/__tests__/queueRunner.test.ts | 91 +- .../src/__tests__/reporter.test.ts | 6 +- .../src/__tests__/todoError.test.ts | 2 +- .../src/__tests__/index.test.ts | 2 - .../src/__tests__/Replaceable.test.ts | 3 +- .../__tests__/printDiffOrStringify.test.ts | 8 +- .../src/__tests__/messages.test.ts | 44 +- .../jest-mock/src/__tests__/index.test.ts | 15 +- .../jest-repl/src/__tests__/jest_repl.test.js | 2 +- .../src/__tests__/CoverageReporter.test.js | 2 +- .../__tests__/GitHubActionsReporter.test.ts | 20 +- .../__tests__/generateEmptyCoverage.test.js | 4 +- .../src/__tests__/resolve.test.ts | 17 +- .../src/__mocks__/createRuntime.js | 2 +- .../__tests__/runtime_require_module.test.js | 2 +- .../__tests__/runtime_require_resolve.test.ts | 4 +- .../src/__tests__/InlineSnapshots.test.ts | 6 +- .../src/__tests__/getCallsite.test.ts | 4 +- .../src/__tests__/ScriptTransformer.test.ts | 2 +- scripts/build.mjs | 4 +- scripts/buildTs.mjs | 6 +- scripts/buildUtils.mjs | 4 +- scripts/bundleTs.mjs | 2 +- scripts/remove-examples.mjs | 2 +- scripts/verifyOldTs.mjs | 2 +- scripts/verifyPnP.mjs | 2 +- scripts/watch.mjs | 2 +- .../version-28.x/Configuration.md | 2 +- .../versioned_docs/version-28.x/Puppeteer.md | 2 +- .../version-29.0/Configuration.md | 2 +- .../versioned_docs/version-29.0/Puppeteer.md | 2 +- .../version-29.1/Configuration.md | 2 +- .../versioned_docs/version-29.1/Puppeteer.md | 2 +- 84 files changed, 1111 insertions(+), 1076 deletions(-) diff --git a/docs/Configuration.md b/docs/Configuration.md index c60b6ea66551..5ecbeef85358 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -1807,7 +1807,7 @@ Example: ```js // my-custom-environment -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; class CustomEnvironment extends NodeEnvironment { constructor(config, context) { diff --git a/docs/Puppeteer.md b/docs/Puppeteer.md index b954c5be25cb..5752f7cba96d 100644 --- a/docs/Puppeteer.md +++ b/docs/Puppeteer.md @@ -84,7 +84,7 @@ const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); const puppeteer = require('puppeteer'); -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); diff --git a/e2e/global-setup-esm/__tests__/test.js b/e2e/global-setup-esm/__tests__/test.js index 2a9dc9e0c339..2678b932b46b 100644 --- a/e2e/global-setup-esm/__tests__/test.js +++ b/e2e/global-setup-esm/__tests__/test.js @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -import os from 'os'; -import path from 'path'; +import * as os from 'os'; +import * as path from 'path'; import fs from 'graceful-fs'; import greeting from '../'; diff --git a/e2e/global-setup-esm/setup.js b/e2e/global-setup-esm/setup.js index 144cca53cf80..7d458b4c8475 100644 --- a/e2e/global-setup-esm/setup.js +++ b/e2e/global-setup-esm/setup.js @@ -4,9 +4,9 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -import crypto from 'crypto'; -import os from 'os'; -import path from 'path'; +import * as crypto from 'crypto'; +import * as os from 'os'; +import * as path from 'path'; import fs from 'graceful-fs'; import jestUtil from 'jest-util'; diff --git a/e2e/global-teardown-esm/__tests__/test.js b/e2e/global-teardown-esm/__tests__/test.js index 6c5dfb67b485..508394b8eb26 100644 --- a/e2e/global-teardown-esm/__tests__/test.js +++ b/e2e/global-teardown-esm/__tests__/test.js @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -import os from 'os'; -import path from 'path'; +import * as os from 'os'; +import * as path from 'path'; import fs from 'graceful-fs'; import greeting from '../'; diff --git a/e2e/global-teardown-esm/teardown.js b/e2e/global-teardown-esm/teardown.js index 314c4bdf6c44..71ab1c045968 100644 --- a/e2e/global-teardown-esm/teardown.js +++ b/e2e/global-teardown-esm/teardown.js @@ -4,9 +4,9 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -import crypto from 'crypto'; -import os from 'os'; -import path from 'path'; +import * as crypto from 'crypto'; +import * as os from 'os'; +import * as path from 'path'; import fs from 'graceful-fs'; import jestUtil from 'jest-util'; diff --git a/e2e/require-main/loader.js b/e2e/require-main/loader.js index bde2634e36e9..229db8cfb93a 100644 --- a/e2e/require-main/loader.js +++ b/e2e/require-main/loader.js @@ -4,7 +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 path from 'path'; +import * as path from 'path'; module.exports = function load(moduleId) { return require(path.join(path.dirname(require.main.filename), moduleId)); diff --git a/e2e/resolve-conditions/deno-env.js b/e2e/resolve-conditions/deno-env.js index 8468ad463dda..f09d42798463 100644 --- a/e2e/resolve-conditions/deno-env.js +++ b/e2e/resolve-conditions/deno-env.js @@ -7,7 +7,7 @@ 'use strict'; -const NodeEnv = require('jest-environment-node').default; +const NodeEnv = require('jest-environment-node').TestEnvironment; module.exports = class DenoEnvWithConditions extends NodeEnv { exportConditions() { diff --git a/e2e/test-environment-async/TestEnvironment.js b/e2e/test-environment-async/TestEnvironment.js index f5e63b28ed2b..55a170905d32 100644 --- a/e2e/test-environment-async/TestEnvironment.js +++ b/e2e/test-environment-async/TestEnvironment.js @@ -9,7 +9,7 @@ const fs = require('fs'); const os = require('os'); -const JSDOMEnvironment = require('jest-environment-jsdom').default; +const JSDOMEnvironment = require('jest-environment-jsdom').TestEnvironment; const {createDirectory} = require('jest-util'); const DIR = `${os.tmpdir()}/jest-test-environment`; diff --git a/e2e/test-environment-circus-async/CircusAsyncHandleTestEventEnvironment.js b/e2e/test-environment-circus-async/CircusAsyncHandleTestEventEnvironment.js index 43df9089c3d4..1d07cc1627df 100644 --- a/e2e/test-environment-circus-async/CircusAsyncHandleTestEventEnvironment.js +++ b/e2e/test-environment-circus-async/CircusAsyncHandleTestEventEnvironment.js @@ -7,7 +7,7 @@ 'use strict'; -const JSDOMEnvironment = require('jest-environment-jsdom').default; +const JSDOMEnvironment = require('jest-environment-jsdom').TestEnvironment; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); diff --git a/e2e/test-environment-circus/CircusHandleTestEventEnvironment.js b/e2e/test-environment-circus/CircusHandleTestEventEnvironment.js index 3b96cffb3b6f..39d230fbf093 100644 --- a/e2e/test-environment-circus/CircusHandleTestEventEnvironment.js +++ b/e2e/test-environment-circus/CircusHandleTestEventEnvironment.js @@ -7,7 +7,7 @@ 'use strict'; -const JSDOMEnvironment = require('jest-environment-jsdom').default; +const JSDOMEnvironment = require('jest-environment-jsdom').TestEnvironment; class TestEnvironment extends JSDOMEnvironment { handleTestEvent(event) { diff --git a/e2e/test-environment/DocblockPragmasEnvironment.js b/e2e/test-environment/DocblockPragmasEnvironment.js index 2f6b1329f4d2..ddbea10a3088 100644 --- a/e2e/test-environment/DocblockPragmasEnvironment.js +++ b/e2e/test-environment/DocblockPragmasEnvironment.js @@ -7,7 +7,7 @@ 'use strict'; -const JSDOMEnvironment = require('jest-environment-jsdom').default; +const JSDOMEnvironment = require('jest-environment-jsdom').TestEnvironment; class TestEnvironment extends JSDOMEnvironment { constructor(config, context) { diff --git a/e2e/test-environment/EsmDefaultEnvironment.js b/e2e/test-environment/EsmDefaultEnvironment.js index 1526a1b8c042..32d84de70a15 100644 --- a/e2e/test-environment/EsmDefaultEnvironment.js +++ b/e2e/test-environment/EsmDefaultEnvironment.js @@ -8,7 +8,7 @@ exports.__esModule = true; -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; class Env extends NodeEnvironment { constructor(config, options) { diff --git a/e2e/transform/transform-environment/environment.ts b/e2e/transform/transform-environment/environment.ts index 9f702529c5d3..fa68228d591f 100644 --- a/e2e/transform/transform-environment/environment.ts +++ b/e2e/transform/transform-environment/environment.ts @@ -5,12 +5,15 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; +import type { + EnvironmentContext, + JestEnvironmentConfig, +} from '@jest/environment'; import NodeEnvironment from 'jest-environment-node'; export default class CustomEnvironment extends NodeEnvironment { - constructor(config: Config.ProjectConfig) { - super(config); + constructor(config: JestEnvironmentConfig, context: EnvironmentContext) { + super(config, context); this.global.one = 1; } } diff --git a/examples/mongodb/mongo-environment.js b/examples/mongodb/mongo-environment.js index c07bd2d4b0a6..eb0130e42f29 100644 --- a/examples/mongodb/mongo-environment.js +++ b/examples/mongodb/mongo-environment.js @@ -1,12 +1,12 @@ -import fs from 'fs'; -import path from 'path'; -import NodeEnvironment from 'jest-environment-node'; +import * as fs from 'fs'; +import * as path from 'path'; +import {TestEnvironment} from 'jest-environment-node'; const globalConfigPath = path.join(__dirname, 'globalConfig.json'); -class MongoEnvironment extends NodeEnvironment { - constructor(config) { - super(config); +class MongoEnvironment extends TestEnvironment { + constructor(config, context) { + super(config, context); } async setup() { diff --git a/examples/mongodb/setup.js b/examples/mongodb/setup.js index ae87f7d78245..8bbc0fa4a2e0 100644 --- a/examples/mongodb/setup.js +++ b/examples/mongodb/setup.js @@ -1,5 +1,5 @@ -import fs from 'fs'; -import path from 'path'; +import * as fs from 'fs'; +import * as path from 'path'; import {MongoMemoryServer} from 'mongodb-memory-server'; const globalConfigPath = path.join(__dirname, 'globalConfig.json'); diff --git a/examples/mongodb/teardown.js b/examples/mongodb/teardown.js index 5a2c4a5f4dec..b7adab52143c 100644 --- a/examples/mongodb/teardown.js +++ b/examples/mongodb/teardown.js @@ -1,5 +1,5 @@ -import fs from 'fs'; -import path from 'path'; +import * as fs from 'fs'; +import * as path from 'path'; const globalConfigPath = path.join(__dirname, 'globalConfig.json'); diff --git a/packages/expect-utils/src/__tests__/isError.test.ts b/packages/expect-utils/src/__tests__/isError.test.ts index 8a25e970f153..90dbf6a9c634 100644 --- a/packages/expect-utils/src/__tests__/isError.test.ts +++ b/packages/expect-utils/src/__tests__/isError.test.ts @@ -16,12 +16,20 @@ import {isError} from '../utils'; // Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/test/AngularSpec.js#L1883 describe('isError', () => { function testErrorFromDifferentContext( - createError: (win: Window | null) => Error, + createError: (win: Window) => Error | null, ) { const iframe = document.createElement('iframe'); document.body.appendChild(iframe); try { - const error = createError(iframe.contentWindow); + const contentWindow = iframe.contentWindow; + + expect(contentWindow).toBeTruthy(); + + if (!contentWindow) { + throw new Error('Dead code'); + } + + const error = createError(contentWindow); expect(isError(error)).toBe(true); } finally { iframe.parentElement!.removeChild(iframe); @@ -38,14 +46,14 @@ describe('isError', () => { }); it('should detect errors from another context', () => { - testErrorFromDifferentContext((win: Window) => new win.Error()); + testErrorFromDifferentContext(win => new win.Error()); }); it('should detect DOMException errors from another context', () => { - testErrorFromDifferentContext((win: Window) => { + testErrorFromDifferentContext(win => { try { win.document.querySelectorAll(''); - } catch (e) { + } catch (e: any) { return e; } return null; diff --git a/packages/expect/src/__tests__/assertionCounts.test.ts b/packages/expect/src/__tests__/assertionCounts.test.ts index 45a37e3a5c4b..0e45883363b3 100644 --- a/packages/expect/src/__tests__/assertionCounts.test.ts +++ b/packages/expect/src/__tests__/assertionCounts.test.ts @@ -36,7 +36,7 @@ describe('.hasAssertions()', () => { }); it('throws if expected is not undefined', () => { - jestExpect(() => { + expect(() => { // @ts-expect-error jestExpect.hasAssertions(2); }).toThrowErrorMatchingSnapshot(); diff --git a/packages/expect/src/__tests__/matchers-toEqual.property.test.ts b/packages/expect/src/__tests__/matchers-toEqual.property.test.ts index 8eda9185012e..c54e39090409 100644 --- a/packages/expect/src/__tests__/matchers-toEqual.property.test.ts +++ b/packages/expect/src/__tests__/matchers-toEqual.property.test.ts @@ -25,7 +25,7 @@ describe('toEqual', () => { }); it('should be symmetric', () => { - const safeExpectEqual = (a, b) => { + const safeExpectEqual = (a: unknown, b: unknown) => { try { expect(a).toEqual(b); return true; diff --git a/packages/expect/src/__tests__/matchers-toStrictEqual.property.test.ts b/packages/expect/src/__tests__/matchers-toStrictEqual.property.test.ts index 8f8bd9a0ef8e..b81858b78423 100644 --- a/packages/expect/src/__tests__/matchers-toStrictEqual.property.test.ts +++ b/packages/expect/src/__tests__/matchers-toStrictEqual.property.test.ts @@ -6,7 +6,7 @@ * */ -import assert from 'assert'; +import * as assert from 'assert'; import fc from 'fast-check'; import expect from '..'; import { @@ -15,7 +15,7 @@ import { } from './__arbitraries__/sharedSettings'; describe('toStrictEqual', () => { - const safeExpectStrictEqual = (a, b) => { + const safeExpectStrictEqual = (a: unknown, b: unknown) => { try { expect(a).toStrictEqual(b); return true; @@ -23,7 +23,7 @@ describe('toStrictEqual', () => { return false; } }; - const safeAssertDeepStrictEqual = (a, b) => { + const safeAssertDeepStrictEqual = (a: unknown, b: unknown) => { try { assert.deepStrictEqual(a, b); return true; diff --git a/packages/expect/src/__tests__/matchers.test.js b/packages/expect/src/__tests__/matchers.test.js index 2dc7c6656e08..39204ec611f9 100644 --- a/packages/expect/src/__tests__/matchers.test.js +++ b/packages/expect/src/__tests__/matchers.test.js @@ -61,7 +61,7 @@ describe('.rejects', () => { }); it('should reject async function to toThrow', async () => { - await expect(async () => { + await jestExpect(async () => { throw new Error('Test'); }).rejects.toThrow('Test'); }); diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 669b297a63a7..b9c248282cdb 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -40,58 +40,57 @@ const createSpy = (fn: jest.Mock) => { return spy; }; -['toBeCalled', 'toHaveBeenCalled'].forEach(called => { - describe(`${called}`, () => { - test('works only on spies or jest.fn', () => { - const fn = function fn() {}; +describe.each(['toBeCalled', 'toHaveBeenCalled'] as const)('%s', called => { + test('works only on spies or jest.fn', () => { + const fn = function fn() {}; - expect(() => jestExpect(fn)[called]()).toThrowErrorMatchingSnapshot(); - }); + expect(() => jestExpect(fn)[called]()).toThrowErrorMatchingSnapshot(); + }); - test('passes when called', () => { - const fn = jest.fn(); - fn('arg0', 'arg1', 'arg2'); - jestExpect(createSpy(fn))[called](); - jestExpect(fn)[called](); - expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); - }); + test('passes when called', () => { + const fn = jest.fn(); + fn('arg0', 'arg1', 'arg2'); + jestExpect(createSpy(fn))[called](); + jestExpect(fn)[called](); + expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); + }); - test('.not passes when called', () => { - const fn = jest.fn(); - const spy = createSpy(fn); + test('.not passes when called', () => { + const fn = jest.fn(); + const spy = createSpy(fn); - jestExpect(spy).not[called](); - jestExpect(fn).not[called](); - expect(() => jestExpect(spy)[called]()).toThrowErrorMatchingSnapshot(); - }); + jestExpect(spy).not[called](); + jestExpect(fn).not[called](); + expect(() => jestExpect(spy)[called]()).toThrowErrorMatchingSnapshot(); + }); - test('fails with any argument passed', () => { - const fn = jest.fn(); + test('fails with any argument passed', () => { + const fn = jest.fn(); - fn(); - expect(() => jestExpect(fn)[called](555)).toThrowErrorMatchingSnapshot(); - }); + fn(); + expect(() => jestExpect(fn)[called](555)).toThrowErrorMatchingSnapshot(); + }); - test('.not fails with any argument passed', () => { - const fn = jest.fn(); + test('.not fails with any argument passed', () => { + const fn = jest.fn(); - expect(() => - jestExpect(fn).not[called](555), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).not[called](555), + ).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn().mockName('named-mock'); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn().mockName('named-mock'); - fn(); - jestExpect(fn)[called](); - expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); - }); + fn(); + jestExpect(fn)[called](); + expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); }); }); -['toBeCalledTimes', 'toHaveBeenCalledTimes'].forEach(calledTimes => { - describe(`${calledTimes}`, () => { +describe.each(['toBeCalledTimes', 'toHaveBeenCalledTimes'] as const)( + '%s', + calledTimes => { test('.not works only on spies or jest.fn', () => { const fn = function fn() {}; @@ -179,17 +178,17 @@ const createSpy = (fn: jest.Mock) => { jestExpect(fn)[calledTimes](2), ).toThrowErrorMatchingSnapshot(); }); - }); -}); + }, +); -[ +describe.each([ 'lastCalledWith', 'toHaveBeenLastCalledWith', 'nthCalledWith', 'toHaveBeenNthCalledWith', 'toBeCalledWith', 'toHaveBeenCalledWith', -].forEach(calledWith => { +] as const)('%s', calledWith => { const caller = function ( callee: (...a: Array) => void, ...args: Array @@ -203,482 +202,466 @@ const createSpy = (fn: jest.Mock) => { callee(...args); } }; - describe(`${calledWith}`, () => { - test('works only on spies or jest.fn', () => { - const fn = function fn() {}; - expect(() => jestExpect(fn)[calledWith]()).toThrowErrorMatchingSnapshot(); - }); + test('works only on spies or jest.fn', () => { + const fn = function fn() {}; - test('works when not called', () => { - const fn = jest.fn(); - caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); - caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); + expect(() => jestExpect(fn)[calledWith]()).toThrowErrorMatchingSnapshot(); + }); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + test('works when not called', () => { + const fn = jest.fn(); + caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); + caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); - test('works with no arguments', () => { - const fn = jest.fn(); - fn(); - caller(jestExpect(createSpy(fn))[calledWith]); - caller(jestExpect(fn)[calledWith]); - }); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo', 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); - test("works with arguments that don't match", () => { - const fn = jest.fn(); - fn('foo', 'bar1'); + test('works with no arguments', () => { + const fn = jest.fn(); + fn(); + caller(jestExpect(createSpy(fn))[calledWith]); + caller(jestExpect(fn)[calledWith]); + }); - caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); - caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); + test("works with arguments that don't match", () => { + const fn = jest.fn(); + fn('foo', 'bar1'); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); + caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); - test("works with arguments that don't match in number of arguments", () => { - const fn = jest.fn(); - fn('foo', 'bar', 'plop'); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo', 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); - caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); + test("works with arguments that don't match in number of arguments", () => { + const fn = jest.fn(); + fn('foo', 'bar', 'plop'); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + caller(jestExpect(createSpy(fn)).not[calledWith], 'foo', 'bar'); + caller(jestExpect(fn).not[calledWith], 'foo', 'bar'); - test("works with arguments that don't match with matchers", () => { - const fn = jest.fn(); - fn('foo', 'bar'); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo', 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); + test("works with arguments that don't match with matchers", () => { + const fn = jest.fn(); + fn('foo', 'bar'); + + caller( + jestExpect(createSpy(fn)).not[calledWith], + jestExpect.any(String), + jestExpect.any(Number), + ); + caller( + jestExpect(fn).not[calledWith], + jestExpect.any(String), + jestExpect.any(Number), + ); + + expect(() => caller( - jestExpect(createSpy(fn)).not[calledWith], - jestExpect.any(String), - jestExpect.any(Number), - ); - caller( - jestExpect(fn).not[calledWith], + jestExpect(fn)[calledWith], jestExpect.any(String), jestExpect.any(Number), - ); - - expect(() => - caller( - jestExpect(fn)[calledWith], - jestExpect.any(String), - jestExpect.any(Number), - ), - ).toThrowErrorMatchingSnapshot(); - }); - - test("works with arguments that don't match with matchers even when argument is undefined", () => { - const fn = jest.fn(); - fn('foo', undefined); + ), + ).toThrowErrorMatchingSnapshot(); + }); - caller( - jestExpect(createSpy(fn)).not[calledWith], - 'foo', - jestExpect.any(String), - ); - caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.any(String)); + test("works with arguments that don't match with matchers even when argument is undefined", () => { + const fn = jest.fn(); + fn('foo', undefined); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo', jestExpect.any(String)), - ).toThrowErrorMatchingSnapshot(); - }); + caller( + jestExpect(createSpy(fn)).not[calledWith], + 'foo', + jestExpect.any(String), + ); + caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.any(String)); - test("works with arguments that don't match in size even if one is an optional matcher", () => { - // issue 12463 - const fn = jest.fn(); - fn('foo'); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo', jestExpect.any(String)), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.optionalFn()); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo', jestExpect.optionalFn()), - ).toThrowErrorMatchingSnapshot(); - }); + test("works with arguments that don't match in size even if one is an optional matcher", () => { + // issue 12463 + const fn = jest.fn(); + fn('foo'); - test('works with arguments that match', () => { - const fn = jest.fn(); - fn('foo', 'bar'); + caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.optionalFn()); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo', jestExpect.optionalFn()), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(createSpy(fn))[calledWith], 'foo', 'bar'); - caller(jestExpect(fn)[calledWith], 'foo', 'bar'); + test('works with arguments that match', () => { + const fn = jest.fn(); + fn('foo', 'bar'); - expect(() => - caller(jestExpect(fn).not[calledWith], 'foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + caller(jestExpect(createSpy(fn))[calledWith], 'foo', 'bar'); + caller(jestExpect(fn)[calledWith], 'foo', 'bar'); - test('works with arguments that match with matchers', () => { - const fn = jest.fn(); - fn('foo', 'bar'); + expect(() => + caller(jestExpect(fn).not[calledWith], 'foo', 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); + test('works with arguments that match with matchers', () => { + const fn = jest.fn(); + fn('foo', 'bar'); + + caller( + jestExpect(createSpy(fn))[calledWith], + jestExpect.any(String), + jestExpect.any(String), + ); + caller( + jestExpect(fn)[calledWith], + jestExpect.any(String), + jestExpect.any(String), + ); + + expect(() => caller( - jestExpect(createSpy(fn))[calledWith], - jestExpect.any(String), - jestExpect.any(String), - ); - caller( - jestExpect(fn)[calledWith], + jestExpect(fn).not[calledWith], jestExpect.any(String), jestExpect.any(String), - ); + ), + ).toThrowErrorMatchingSnapshot(); + }); - expect(() => - caller( - jestExpect(fn).not[calledWith], - jestExpect.any(String), - jestExpect.any(String), - ), - ).toThrowErrorMatchingSnapshot(); - }); + test('works with trailing undefined arguments', () => { + const fn = jest.fn(); + fn('foo', undefined); - test('works with trailing undefined arguments', () => { - const fn = jest.fn(); - fn('foo', undefined); + expect(() => + caller(jestExpect(fn)[calledWith], 'foo'), + ).toThrowErrorMatchingSnapshot(); + }); - expect(() => - caller(jestExpect(fn)[calledWith], 'foo'), - ).toThrowErrorMatchingSnapshot(); - }); + test('works with trailing undefined arguments if requested by the match query', () => { + const fn = jest.fn(); + fn('foo', undefined); - test('works with trailing undefined arguments if requested by the match query', () => { - const fn = jest.fn(); - fn('foo', undefined); + caller(jestExpect(fn)[calledWith], 'foo', undefined); + expect(() => + caller(jestExpect(fn).not[calledWith], 'foo', undefined), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn)[calledWith], 'foo', undefined); - expect(() => - caller(jestExpect(fn).not[calledWith], 'foo', undefined), - ).toThrowErrorMatchingSnapshot(); - }); + test('works with trailing undefined arguments when explicitly requested as optional by matcher', () => { + // issue 12463 + const fn = jest.fn(); + fn('foo', undefined); - test('works with trailing undefined arguments when explicitly requested as optional by matcher', () => { - // issue 12463 - const fn = jest.fn(); - fn('foo', undefined); + caller(jestExpect(fn)[calledWith], 'foo', jestExpect.optionalFn()); + expect(() => + caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.optionalFn()), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn)[calledWith], 'foo', jestExpect.optionalFn()); - expect(() => - caller(jestExpect(fn).not[calledWith], 'foo', jestExpect.optionalFn()), - ).toThrowErrorMatchingSnapshot(); - }); + test('works with Map', () => { + const fn = jest.fn(); + + const m1 = new Map([ + [1, 2], + [2, 1], + ]); + const m2 = new Map([ + [1, 2], + [2, 1], + ]); + const m3 = new Map([ + ['a', 'b'], + ['b', 'a'], + ]); + + fn(m1); + + caller(jestExpect(fn)[calledWith], m2); + caller(jestExpect(fn).not[calledWith], m3); + + expect(() => + caller(jestExpect(fn).not[calledWith], m2), + ).toThrowErrorMatchingSnapshot(); + expect(() => + caller(jestExpect(fn)[calledWith], m3), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with Map', () => { - const fn = jest.fn(); + test('works with Set', () => { + const fn = jest.fn(); - const m1 = new Map([ - [1, 2], - [2, 1], - ]); - const m2 = new Map([ - [1, 2], - [2, 1], - ]); - const m3 = new Map([ - ['a', 'b'], - ['b', 'a'], - ]); + const s1 = new Set([1, 2]); + const s2 = new Set([1, 2]); + const s3 = new Set([3, 4]); - fn(m1); + fn(s1); - caller(jestExpect(fn)[calledWith], m2); - caller(jestExpect(fn).not[calledWith], m3); + caller(jestExpect(fn)[calledWith], s2); + caller(jestExpect(fn).not[calledWith], s3); - expect(() => - caller(jestExpect(fn).not[calledWith], m2), - ).toThrowErrorMatchingSnapshot(); - expect(() => - caller(jestExpect(fn)[calledWith], m3), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn).not[calledWith], s2), + ).toThrowErrorMatchingSnapshot(); + expect(() => + caller(jestExpect(fn)[calledWith], s3), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with Set', () => { - const fn = jest.fn(); + test('works with Immutable.js objects', () => { + const fn = jest.fn(); + const directlyCreated = Immutable.Map([['a', {b: 'c'}]]); + const indirectlyCreated = Immutable.Map().set('a', {b: 'c'}); + fn(directlyCreated, indirectlyCreated); - const s1 = new Set([1, 2]); - const s2 = new Set([1, 2]); - const s3 = new Set([3, 4]); + caller(jestExpect(fn)[calledWith], indirectlyCreated, directlyCreated); - fn(s1); + expect(() => + caller( + jestExpect(fn).not[calledWith], + indirectlyCreated, + directlyCreated, + ), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn)[calledWith], s2); - caller(jestExpect(fn).not[calledWith], s3); + const basicCalledWith = [ + 'lastCalledWith', + 'toHaveBeenLastCalledWith', + 'toBeCalledWith', + 'toHaveBeenCalledWith', + ]; + + if (basicCalledWith.indexOf(calledWith) >= 0) { + test('works with many arguments', () => { + const fn = jest.fn(); + fn('foo1', 'bar'); + fn('foo', 'bar1'); + fn('foo', 'bar'); + + jestExpect(fn)[calledWith]('foo', 'bar'); expect(() => - caller(jestExpect(fn).not[calledWith], s2), - ).toThrowErrorMatchingSnapshot(); - expect(() => - caller(jestExpect(fn)[calledWith], s3), + jestExpect(fn).not[calledWith]('foo', 'bar'), ).toThrowErrorMatchingSnapshot(); }); - test('works with Immutable.js objects', () => { + test("works with many arguments that don't match", () => { const fn = jest.fn(); - const directlyCreated = Immutable.Map([['a', {b: 'c'}]]); - const indirectlyCreated = Immutable.Map().set('a', {b: 'c'}); - fn(directlyCreated, indirectlyCreated); + fn('foo', 'bar1'); + fn('foo', 'bar2'); + fn('foo', 'bar3'); - caller(jestExpect(fn)[calledWith], indirectlyCreated, directlyCreated); + jestExpect(fn).not[calledWith]('foo', 'bar'); expect(() => - caller( - jestExpect(fn).not[calledWith], - indirectlyCreated, - directlyCreated, - ), + jestExpect(fn)[calledWith]('foo', 'bar'), ).toThrowErrorMatchingSnapshot(); }); + } - const basicCalledWith = [ - 'lastCalledWith', - 'toHaveBeenLastCalledWith', - 'toBeCalledWith', - 'toHaveBeenCalledWith', - ]; - - if (basicCalledWith.indexOf(calledWith) >= 0) { - test('works with many arguments', () => { - const fn = jest.fn(); - fn('foo1', 'bar'); - fn('foo', 'bar1'); - fn('foo', 'bar'); - - jestExpect(fn)[calledWith]('foo', 'bar'); - - expect(() => - jestExpect(fn).not[calledWith]('foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); - - test("works with many arguments that don't match", () => { - const fn = jest.fn(); - fn('foo', 'bar1'); - fn('foo', 'bar2'); - fn('foo', 'bar3'); - - jestExpect(fn).not[calledWith]('foo', 'bar'); + const nthCalled = ['toHaveBeenNthCalledWith', 'nthCalledWith']; + if (nthCalled.indexOf(calledWith) >= 0) { + test('works with three calls', () => { + const fn = jest.fn(); + fn('foo1', 'bar'); + fn('foo', 'bar1'); + fn('foo', 'bar'); - expect(() => - jestExpect(fn)[calledWith]('foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); - } + jestExpect(fn)[calledWith](1, 'foo1', 'bar'); + jestExpect(fn)[calledWith](2, 'foo', 'bar1'); + jestExpect(fn)[calledWith](3, 'foo', 'bar'); - const nthCalled = ['toHaveBeenNthCalledWith', 'nthCalledWith']; - if (nthCalled.indexOf(calledWith) >= 0) { - test('works with three calls', () => { - const fn = jest.fn(); - fn('foo1', 'bar'); - fn('foo', 'bar1'); - fn('foo', 'bar'); + expect(() => { + jestExpect(fn).not[calledWith](1, 'foo1', 'bar'); + }).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[calledWith](1, 'foo1', 'bar'); - jestExpect(fn)[calledWith](2, 'foo', 'bar1'); - jestExpect(fn)[calledWith](3, 'foo', 'bar'); + test('positive throw matcher error for n that is not positive integer', async () => { + const fn = jest.fn(); + fn('foo1', 'bar'); - expect(() => { - jestExpect(fn).not[calledWith](1, 'foo1', 'bar'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn)[calledWith](0, 'foo1', 'bar'); + }).toThrowErrorMatchingSnapshot(); + }); - test('positive throw matcher error for n that is not positive integer', async () => { - const fn = jest.fn(); - fn('foo1', 'bar'); + test('positive throw matcher error for n that is not integer', async () => { + const fn = jest.fn(); + fn('foo1', 'bar'); - expect(() => { - jestExpect(fn)[calledWith](0, 'foo1', 'bar'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn)[calledWith](0.1, 'foo1', 'bar'); + }).toThrowErrorMatchingSnapshot(); + }); - test('positive throw matcher error for n that is not integer', async () => { - const fn = jest.fn(); - fn('foo1', 'bar'); + test('negative throw matcher error for n that is not integer', async () => { + const fn = jest.fn(); + fn('foo1', 'bar'); - expect(() => { - jestExpect(fn)[calledWith](0.1, 'foo1', 'bar'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn).not[calledWith](Infinity, 'foo1', 'bar'); + }).toThrowErrorMatchingSnapshot(); + }); + } - test('negative throw matcher error for n that is not integer', async () => { - const fn = jest.fn(); - fn('foo1', 'bar'); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn().mockName('named-mock'); + fn('foo', 'bar'); - expect(() => { - jestExpect(fn).not[calledWith](Infinity, 'foo1', 'bar'); - }).toThrowErrorMatchingSnapshot(); - }); - } + caller(jestExpect(fn)[calledWith], 'foo', 'bar'); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn().mockName('named-mock'); - fn('foo', 'bar'); + expect(() => + caller(jestExpect(fn).not[calledWith], 'foo', 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); +}); - caller(jestExpect(fn)[calledWith], 'foo', 'bar'); +describe.each(['toReturn', 'toHaveReturned'] as const)('%s', returned => { + test('.not works only on jest.fn', () => { + const fn = function fn() {}; - expect(() => - caller(jestExpect(fn).not[calledWith], 'foo', 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => jestExpect(fn).not[returned]()).toThrowErrorMatchingSnapshot(); }); -}); -['toReturn', 'toHaveReturned'].forEach(returned => { - describe(`${returned}`, () => { - test('.not works only on jest.fn', () => { - const fn = function fn() {}; + test('throw matcher error if received is spy', () => { + const spy = createSpy(jest.fn()); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => jestExpect(spy)[returned]()).toThrowErrorMatchingSnapshot(); + }); - test('throw matcher error if received is spy', () => { - const spy = createSpy(jest.fn()); + test('passes when returned', () => { + const fn = jest.fn(() => 42); + fn(); + jestExpect(fn)[returned](); + expect(() => jestExpect(fn).not[returned]()).toThrowErrorMatchingSnapshot(); + }); - expect(() => jestExpect(spy)[returned]()).toThrowErrorMatchingSnapshot(); - }); + test('passes when undefined is returned', () => { + const fn = jest.fn(() => undefined); + fn(); + jestExpect(fn)[returned](); + expect(() => jestExpect(fn).not[returned]()).toThrowErrorMatchingSnapshot(); + }); - test('passes when returned', () => { - const fn = jest.fn(() => 42); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + test('passes when at least one call does not throw', () => { + const fn = jest.fn(causeError => { + if (causeError) { + throw new Error('Error!'); + } - test('passes when undefined is returned', () => { - const fn = jest.fn(() => undefined); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); + return 42; }); - test('passes when at least one call does not throw', () => { - const fn = jest.fn(causeError => { - if (causeError) { - throw new Error('Error!'); - } - - return 42; - }); + fn(false); - fn(false); + try { + fn(true); + } catch { + // ignore error + } - try { - fn(true); - } catch { - // ignore error - } + fn(false); - fn(false); + jestExpect(fn)[returned](); + expect(() => jestExpect(fn).not[returned]()).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + test('.not passes when not returned', () => { + const fn = jest.fn(); - test('.not passes when not returned', () => { - const fn = jest.fn(); + jestExpect(fn).not[returned](); + expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + test('.not passes when all calls throw', () => { + const fn = jest.fn(() => { + throw new Error('Error!'); }); - test('.not passes when all calls throw', () => { - const fn = jest.fn(() => { - throw new Error('Error!'); - }); + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + jestExpect(fn).not[returned](); + expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + test('.not passes when a call throws undefined', () => { + const fn = jest.fn(() => { + // eslint-disable-next-line no-throw-literal + throw undefined; }); - test('.not passes when a call throws undefined', () => { - const fn = jest.fn(() => { - // eslint-disable-next-line no-throw-literal - throw undefined; - }); + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + jestExpect(fn).not[returned](); + expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); - }); + test('fails with any argument passed', () => { + const fn = jest.fn(); - test('fails with any argument passed', () => { - const fn = jest.fn(); + fn(); + expect(() => jestExpect(fn)[returned](555)).toThrowErrorMatchingSnapshot(); + }); - fn(); - expect(() => - jestExpect(fn)[returned](555), - ).toThrowErrorMatchingSnapshot(); - }); + test('.not fails with any argument passed', () => { + const fn = jest.fn(); - test('.not fails with any argument passed', () => { - const fn = jest.fn(); + expect(() => + jestExpect(fn).not[returned](555), + ).toThrowErrorMatchingSnapshot(); + }); - expect(() => - jestExpect(fn).not[returned](555), - ).toThrowErrorMatchingSnapshot(); - }); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn(() => 42).mockName('named-mock'); + fn(); + jestExpect(fn)[returned](); + expect(() => jestExpect(fn).not[returned]()).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn(() => 42).mockName('named-mock'); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock<(value: number) => number> = jest.fn(value => { + if (value === 0) { + // Before returning from the base case of recursion, none of the + // calls have returned yet. + jestExpect(fn).not[returned](); + expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + return 0; + } else { + return value + fn(value - 1); + } }); - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - // Before returning from the base case of recursion, none of the - // calls have returned yet. - jestExpect(fn).not[returned](); - expect(() => - jestExpect(fn)[returned](), - ).toThrowErrorMatchingSnapshot(); - return 0; - } else { - return value + fn(value - 1); - } - }); - - fn(3); - }); + fn(3); }); }); -['toReturnTimes', 'toHaveReturnedTimes'].forEach(returnedTimes => { - describe(`${returnedTimes}`, () => { +describe.each(['toReturnTimes', 'toHaveReturnedTimes'] as const)( + '%s', + returnedTimes => { test('throw matcher error if received is spy', () => { const spy = createSpy(jest.fn()); @@ -827,7 +810,7 @@ const createSpy = (fn: jest.Mock) => { test('incomplete recursive calls are handled properly', () => { // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { + const fn: jest.Mock<(value: number) => number> = jest.fn(value => { if (value === 0) { return 0; } else { @@ -847,17 +830,17 @@ const createSpy = (fn: jest.Mock) => { fn(3); }); - }); -}); + }, +); -[ +describe.each([ 'lastReturnedWith', 'toHaveLastReturnedWith', 'nthReturnedWith', 'toHaveNthReturnedWith', 'toReturnWith', 'toHaveReturnedWith', -].forEach(returnedWith => { +] as const)('%s', returnedWith => { const caller = function ( callee: (...a: Array) => void, ...args: Array @@ -872,395 +855,391 @@ const createSpy = (fn: jest.Mock) => { } }; - describe(`${returnedWith}`, () => { - test('works only on spies or jest.fn', () => { - const fn = function fn() {}; + test('works only on spies or jest.fn', () => { + const fn = function fn() {}; - expect(() => - jestExpect(fn)[returnedWith](), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => jestExpect(fn)[returnedWith]()).toThrowErrorMatchingSnapshot(); + }); - test('works when not called', () => { - const fn = jest.fn(); - caller(jestExpect(fn).not[returnedWith], 'foo'); + test('works when not called', () => { + const fn = jest.fn(); + caller(jestExpect(fn).not[returnedWith], 'foo'); - expect(() => - caller(jestExpect(fn)[returnedWith], 'foo'), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn)[returnedWith], 'foo'), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with no arguments', () => { - const fn = jest.fn(); - fn(); - caller(jestExpect(fn)[returnedWith]); - }); + test('works with no arguments', () => { + const fn = jest.fn(); + fn(); + caller(jestExpect(fn)[returnedWith]); + }); - test('works with argument that does not match', () => { - const fn = jest.fn(() => 'foo'); - fn(); + test('works with argument that does not match', () => { + const fn = jest.fn(() => 'foo'); + fn(); - caller(jestExpect(fn).not[returnedWith], 'bar'); + caller(jestExpect(fn).not[returnedWith], 'bar'); - expect(() => - caller(jestExpect(fn)[returnedWith], 'bar'), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn)[returnedWith], 'bar'), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with argument that does match', () => { - const fn = jest.fn(() => 'foo'); - fn(); + test('works with argument that does match', () => { + const fn = jest.fn(() => 'foo'); + fn(); - caller(jestExpect(fn)[returnedWith], 'foo'); + caller(jestExpect(fn)[returnedWith], 'foo'); - expect(() => - caller(jestExpect(fn).not[returnedWith], 'foo'), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn).not[returnedWith], 'foo'), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with undefined', () => { - const fn = jest.fn(() => undefined); - fn(); + test('works with undefined', () => { + const fn = jest.fn(() => undefined); + fn(); - caller(jestExpect(fn)[returnedWith], undefined); + caller(jestExpect(fn)[returnedWith], undefined); - expect(() => - caller(jestExpect(fn).not[returnedWith], undefined), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn).not[returnedWith], undefined), + ).toThrowErrorMatchingSnapshot(); + }); - test('works with Map', () => { - const m1 = new Map([ - [1, 2], - [2, 1], - ]); - const m2 = new Map([ - [1, 2], - [2, 1], - ]); - const m3 = new Map([ - ['a', 'b'], - ['b', 'a'], - ]); - - const fn = jest.fn(() => m1); - fn(); + test('works with Map', () => { + const m1 = new Map([ + [1, 2], + [2, 1], + ]); + const m2 = new Map([ + [1, 2], + [2, 1], + ]); + const m3 = new Map([ + ['a', 'b'], + ['b', 'a'], + ]); + + const fn = jest.fn(() => m1); + fn(); + + caller(jestExpect(fn)[returnedWith], m2); + caller(jestExpect(fn).not[returnedWith], m3); + + expect(() => + caller(jestExpect(fn).not[returnedWith], m2), + ).toThrowErrorMatchingSnapshot(); + expect(() => + caller(jestExpect(fn)[returnedWith], m3), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn)[returnedWith], m2); - caller(jestExpect(fn).not[returnedWith], m3); + test('works with Set', () => { + const s1 = new Set([1, 2]); + const s2 = new Set([1, 2]); + const s3 = new Set([3, 4]); - expect(() => - caller(jestExpect(fn).not[returnedWith], m2), - ).toThrowErrorMatchingSnapshot(); - expect(() => - caller(jestExpect(fn)[returnedWith], m3), - ).toThrowErrorMatchingSnapshot(); - }); + const fn = jest.fn(() => s1); + fn(); - test('works with Set', () => { - const s1 = new Set([1, 2]); - const s2 = new Set([1, 2]); - const s3 = new Set([3, 4]); + caller(jestExpect(fn)[returnedWith], s2); + caller(jestExpect(fn).not[returnedWith], s3); - const fn = jest.fn(() => s1); - fn(); + expect(() => + caller(jestExpect(fn).not[returnedWith], s2), + ).toThrowErrorMatchingSnapshot(); + expect(() => + caller(jestExpect(fn)[returnedWith], s3), + ).toThrowErrorMatchingSnapshot(); + }); - caller(jestExpect(fn)[returnedWith], s2); - caller(jestExpect(fn).not[returnedWith], s3); + test('works with Immutable.js objects directly created', () => { + const directlyCreated = Immutable.Map([['a', {b: 'c'}]]); + const fn = jest.fn(() => directlyCreated); + fn(); - expect(() => - caller(jestExpect(fn).not[returnedWith], s2), - ).toThrowErrorMatchingSnapshot(); - expect(() => - caller(jestExpect(fn)[returnedWith], s3), - ).toThrowErrorMatchingSnapshot(); + caller(jestExpect(fn)[returnedWith], directlyCreated); + + expect(() => + caller(jestExpect(fn).not[returnedWith], directlyCreated), + ).toThrowErrorMatchingSnapshot(); + }); + + test('works with Immutable.js objects indirectly created', () => { + const indirectlyCreated = Immutable.Map().set('a', {b: 'c'}); + const fn = jest.fn(() => indirectlyCreated); + fn(); + + caller(jestExpect(fn)[returnedWith], indirectlyCreated); + + expect(() => + caller(jestExpect(fn).not[returnedWith], indirectlyCreated), + ).toThrowErrorMatchingSnapshot(); + }); + + test('a call that throws is not considered to have returned', () => { + const fn = jest.fn(() => { + throw new Error('Error!'); }); - test('works with Immutable.js objects directly created', () => { - const directlyCreated = Immutable.Map([['a', {b: 'c'}]]); - const fn = jest.fn(() => directlyCreated); + try { fn(); + } catch { + // ignore error + } - caller(jestExpect(fn)[returnedWith], directlyCreated); + // It doesn't matter what return value is tested if the call threw + caller(jestExpect(fn).not[returnedWith], 'foo'); + caller(jestExpect(fn).not[returnedWith], null); + caller(jestExpect(fn).not[returnedWith], undefined); - expect(() => - caller(jestExpect(fn).not[returnedWith], directlyCreated), - ).toThrowErrorMatchingSnapshot(); + expect(() => + caller(jestExpect(fn)[returnedWith], undefined), + ).toThrowErrorMatchingSnapshot(); + }); + + test('a call that throws undefined is not considered to have returned', () => { + const fn = jest.fn(() => { + // eslint-disable-next-line no-throw-literal + throw undefined; }); - test('works with Immutable.js objects indirectly created', () => { - const indirectlyCreated = Immutable.Map().set('a', {b: 'c'}); - const fn = jest.fn(() => indirectlyCreated); + try { fn(); + } catch { + // ignore error + } - caller(jestExpect(fn)[returnedWith], indirectlyCreated); + // It doesn't matter what return value is tested if the call threw + caller(jestExpect(fn).not[returnedWith], 'foo'); + caller(jestExpect(fn).not[returnedWith], null); + caller(jestExpect(fn).not[returnedWith], undefined); - expect(() => - caller(jestExpect(fn).not[returnedWith], indirectlyCreated), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + caller(jestExpect(fn)[returnedWith], undefined), + ).toThrowErrorMatchingSnapshot(); + }); - test('a call that throws is not considered to have returned', () => { - const fn = jest.fn(() => { - throw new Error('Error!'); - }); + const basicReturnedWith = ['toHaveReturnedWith', 'toReturnWith']; + if (basicReturnedWith.indexOf(returnedWith) >= 0) { + describe('returnedWith', () => { + test('works with more calls than the limit', () => { + const fn = jest.fn(); + fn.mockReturnValueOnce('foo1'); + fn.mockReturnValueOnce('foo2'); + fn.mockReturnValueOnce('foo3'); + fn.mockReturnValueOnce('foo4'); + fn.mockReturnValueOnce('foo5'); + fn.mockReturnValueOnce('foo6'); - try { fn(); - } catch { - // ignore error - } - - // It doesn't matter what return value is tested if the call threw - caller(jestExpect(fn).not[returnedWith], 'foo'); - caller(jestExpect(fn).not[returnedWith], null); - caller(jestExpect(fn).not[returnedWith], undefined); + fn(); + fn(); + fn(); + fn(); + fn(); - expect(() => - caller(jestExpect(fn)[returnedWith], undefined), - ).toThrowErrorMatchingSnapshot(); - }); + jestExpect(fn).not[returnedWith]('bar'); - test('a call that throws undefined is not considered to have returned', () => { - const fn = jest.fn(() => { - // eslint-disable-next-line no-throw-literal - throw undefined; + expect(() => { + jestExpect(fn)[returnedWith]('bar'); + }).toThrowErrorMatchingSnapshot(); }); - try { - fn(); - } catch { - // ignore error - } + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock<(value: number) => number> = jest.fn(value => { + if (value === 0) { + // Before returning from the base case of recursion, none of the + // calls have returned yet. + // This test ensures that the incomplete calls are not incorrectly + // interpreted as have returned undefined + jestExpect(fn).not[returnedWith](undefined); + expect(() => + jestExpect(fn)[returnedWith](undefined), + ).toThrowErrorMatchingSnapshot(); - // It doesn't matter what return value is tested if the call threw - caller(jestExpect(fn).not[returnedWith], 'foo'); - caller(jestExpect(fn).not[returnedWith], null); - caller(jestExpect(fn).not[returnedWith], undefined); + return 0; + } else { + return value + fn(value - 1); + } + }); - expect(() => - caller(jestExpect(fn)[returnedWith], undefined), - ).toThrowErrorMatchingSnapshot(); + fn(3); + }); }); + } - const basicReturnedWith = ['toHaveReturnedWith', 'toReturnWith']; - if (basicReturnedWith.indexOf(returnedWith) >= 0) { - describe('returnedWith', () => { - test('works with more calls than the limit', () => { - const fn = jest.fn(); - fn.mockReturnValueOnce('foo1'); - fn.mockReturnValueOnce('foo2'); - fn.mockReturnValueOnce('foo3'); - fn.mockReturnValueOnce('foo4'); - fn.mockReturnValueOnce('foo5'); - fn.mockReturnValueOnce('foo6'); - - fn(); - fn(); - fn(); - fn(); - fn(); - fn(); - - jestExpect(fn).not[returnedWith]('bar'); - - expect(() => { - jestExpect(fn)[returnedWith]('bar'); - }).toThrowErrorMatchingSnapshot(); - }); - - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - // Before returning from the base case of recursion, none of the - // calls have returned yet. - // This test ensures that the incomplete calls are not incorrectly - // interpreted as have returned undefined - jestExpect(fn).not[returnedWith](undefined); - expect(() => - jestExpect(fn)[returnedWith](undefined), - ).toThrowErrorMatchingSnapshot(); + const nthReturnedWith = ['toHaveNthReturnedWith', 'nthReturnedWith']; + if (nthReturnedWith.indexOf(returnedWith) >= 0) { + describe('nthReturnedWith', () => { + test('works with three calls', () => { + const fn = jest.fn(); + fn.mockReturnValueOnce('foo1'); + fn.mockReturnValueOnce('foo2'); + fn.mockReturnValueOnce('foo3'); + fn(); + fn(); + fn(); - return 0; - } else { - return value + fn(value - 1); - } - }); + jestExpect(fn)[returnedWith](1, 'foo1'); + jestExpect(fn)[returnedWith](2, 'foo2'); + jestExpect(fn)[returnedWith](3, 'foo3'); - fn(3); - }); + expect(() => { + jestExpect(fn).not[returnedWith](1, 'foo1'); + jestExpect(fn).not[returnedWith](2, 'foo2'); + jestExpect(fn).not[returnedWith](3, 'foo3'); + }).toThrowErrorMatchingSnapshot(); }); - } - const nthReturnedWith = ['toHaveNthReturnedWith', 'nthReturnedWith']; - if (nthReturnedWith.indexOf(returnedWith) >= 0) { - describe('nthReturnedWith', () => { - test('works with three calls', () => { - const fn = jest.fn(); - fn.mockReturnValueOnce('foo1'); - fn.mockReturnValueOnce('foo2'); - fn.mockReturnValueOnce('foo3'); - fn(); - fn(); - fn(); - - jestExpect(fn)[returnedWith](1, 'foo1'); - jestExpect(fn)[returnedWith](2, 'foo2'); - jestExpect(fn)[returnedWith](3, 'foo3'); - - expect(() => { - jestExpect(fn).not[returnedWith](1, 'foo1'); - jestExpect(fn).not[returnedWith](2, 'foo2'); - jestExpect(fn).not[returnedWith](3, 'foo3'); - }).toThrowErrorMatchingSnapshot(); - }); - - test('should replace 1st, 2nd, 3rd with first, second, third', async () => { - const fn = jest.fn(); - fn.mockReturnValueOnce('foo1'); - fn.mockReturnValueOnce('foo2'); - fn.mockReturnValueOnce('foo3'); - fn(); - fn(); - fn(); - - expect(() => { - jestExpect(fn)[returnedWith](1, 'bar1'); - jestExpect(fn)[returnedWith](2, 'bar2'); - jestExpect(fn)[returnedWith](3, 'bar3'); - }).toThrowErrorMatchingSnapshot(); - - expect(() => { - jestExpect(fn).not[returnedWith](1, 'foo1'); - jestExpect(fn).not[returnedWith](2, 'foo2'); - jestExpect(fn).not[returnedWith](3, 'foo3'); - }).toThrowErrorMatchingSnapshot(); - }); + test('should replace 1st, 2nd, 3rd with first, second, third', async () => { + const fn = jest.fn(); + fn.mockReturnValueOnce('foo1'); + fn.mockReturnValueOnce('foo2'); + fn.mockReturnValueOnce('foo3'); + fn(); + fn(); + fn(); - test('positive throw matcher error for n that is not positive integer', async () => { - const fn = jest.fn(() => 'foo'); - fn(); + expect(() => { + jestExpect(fn)[returnedWith](1, 'bar1'); + jestExpect(fn)[returnedWith](2, 'bar2'); + jestExpect(fn)[returnedWith](3, 'bar3'); + }).toThrowErrorMatchingSnapshot(); - expect(() => { - jestExpect(fn)[returnedWith](0, 'foo'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn).not[returnedWith](1, 'foo1'); + jestExpect(fn).not[returnedWith](2, 'foo2'); + jestExpect(fn).not[returnedWith](3, 'foo3'); + }).toThrowErrorMatchingSnapshot(); + }); - test('should reject nth value greater than number of calls', async () => { - const fn = jest.fn(() => 'foo'); - fn(); - fn(); - fn(); + test('positive throw matcher error for n that is not positive integer', async () => { + const fn = jest.fn(() => 'foo'); + fn(); - expect(() => { - jestExpect(fn)[returnedWith](4, 'foo'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn)[returnedWith](0, 'foo'); + }).toThrowErrorMatchingSnapshot(); + }); - test('positive throw matcher error for n that is not integer', async () => { - const fn = jest.fn(() => 'foo'); - fn('foo'); + test('should reject nth value greater than number of calls', async () => { + const fn = jest.fn(() => 'foo'); + fn(); + fn(); + fn(); - expect(() => { - jestExpect(fn)[returnedWith](0.1, 'foo'); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn)[returnedWith](4, 'foo'); + }).toThrowErrorMatchingSnapshot(); + }); - test('negative throw matcher error for n that is not number', async () => { - const fn = jest.fn(() => 'foo'); - fn('foo'); + test('positive throw matcher error for n that is not integer', async () => { + const fn = jest.fn(() => 'foo'); + fn('foo'); - expect(() => { - jestExpect(fn).not[returnedWith](); - }).toThrowErrorMatchingSnapshot(); - }); + expect(() => { + jestExpect(fn)[returnedWith](0.1, 'foo'); + }).toThrowErrorMatchingSnapshot(); + }); - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - return 0; - } else { - const recursiveResult = fn(value - 1); - - if (value === 2) { - // Only 2 of the recursive calls have returned at this point - jestExpect(fn).not[returnedWith](1, 6); - jestExpect(fn).not[returnedWith](2, 3); - jestExpect(fn)[returnedWith](3, 1); - jestExpect(fn)[returnedWith](4, 0); - - expect(() => - jestExpect(fn)[returnedWith](1, 6), - ).toThrowErrorMatchingSnapshot(); - expect(() => - jestExpect(fn)[returnedWith](2, 3), - ).toThrowErrorMatchingSnapshot(); - expect(() => - jestExpect(fn).not[returnedWith](3, 1), - ).toThrowErrorMatchingSnapshot(); - expect(() => - jestExpect(fn).not[returnedWith](4, 0), - ).toThrowErrorMatchingSnapshot(); - } - - return value + recursiveResult; - } - }); + test('negative throw matcher error for n that is not number', async () => { + const fn = jest.fn(() => 'foo'); + fn('foo'); - fn(3); - }); + expect(() => { + jestExpect(fn).not[returnedWith](); + }).toThrowErrorMatchingSnapshot(); }); - } - const lastReturnedWith = ['toHaveLastReturnedWith', 'lastReturnedWith']; - if (lastReturnedWith.indexOf(returnedWith) >= 0) { - describe('lastReturnedWith', () => { - test('works with three calls', () => { - const fn = jest.fn(); - fn.mockReturnValueOnce('foo1'); - fn.mockReturnValueOnce('foo2'); - fn.mockReturnValueOnce('foo3'); - fn(); - fn(); - fn(); - - jestExpect(fn)[returnedWith]('foo3'); - - expect(() => { - jestExpect(fn).not[returnedWith]('foo3'); - }).toThrowErrorMatchingSnapshot(); - }); + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock<(value: number) => number> = jest.fn(value => { + if (value === 0) { + return 0; + } else { + const recursiveResult = fn(value - 1); + + if (value === 2) { + // Only 2 of the recursive calls have returned at this point + jestExpect(fn).not[returnedWith](1, 6); + jestExpect(fn).not[returnedWith](2, 3); + jestExpect(fn)[returnedWith](3, 1); + jestExpect(fn)[returnedWith](4, 0); - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - // Before returning from the base case of recursion, none of the - // calls have returned yet. - jestExpect(fn).not[returnedWith](0); expect(() => - jestExpect(fn)[returnedWith](0), + jestExpect(fn)[returnedWith](1, 6), + ).toThrowErrorMatchingSnapshot(); + expect(() => + jestExpect(fn)[returnedWith](2, 3), + ).toThrowErrorMatchingSnapshot(); + expect(() => + jestExpect(fn).not[returnedWith](3, 1), + ).toThrowErrorMatchingSnapshot(); + expect(() => + jestExpect(fn).not[returnedWith](4, 0), ).toThrowErrorMatchingSnapshot(); - return 0; - } else { - return value + fn(value - 1); } - }); - fn(3); + return value + recursiveResult; + } }); + + fn(3); }); - } + }); + } - test('includes the custom mock name in the error message', () => { - const fn = jest.fn().mockName('named-mock'); - caller(jestExpect(fn).not[returnedWith], 'foo'); + const lastReturnedWith = ['toHaveLastReturnedWith', 'lastReturnedWith']; + if (lastReturnedWith.indexOf(returnedWith) >= 0) { + describe('lastReturnedWith', () => { + test('works with three calls', () => { + const fn = jest.fn(); + fn.mockReturnValueOnce('foo1'); + fn.mockReturnValueOnce('foo2'); + fn.mockReturnValueOnce('foo3'); + fn(); + fn(); + fn(); - expect(() => - caller(jestExpect(fn)[returnedWith], 'foo'), - ).toThrowErrorMatchingSnapshot(); + jestExpect(fn)[returnedWith]('foo3'); + + expect(() => { + jestExpect(fn).not[returnedWith]('foo3'); + }).toThrowErrorMatchingSnapshot(); + }); + + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock<(value: number) => number> = jest.fn(value => { + if (value === 0) { + // Before returning from the base case of recursion, none of the + // calls have returned yet. + jestExpect(fn).not[returnedWith](0); + expect(() => + jestExpect(fn)[returnedWith](0), + ).toThrowErrorMatchingSnapshot(); + return 0; + } else { + return value + fn(value - 1); + } + }); + + fn(3); + }); }); + } + + test('includes the custom mock name in the error message', () => { + const fn = jest.fn().mockName('named-mock'); + caller(jestExpect(fn).not[returnedWith], 'foo'); + + expect(() => + caller(jestExpect(fn)[returnedWith], 'foo'), + ).toThrowErrorMatchingSnapshot(); }); }); diff --git a/packages/expect/src/__tests__/toThrowMatchers.test.ts b/packages/expect/src/__tests__/toThrowMatchers.test.ts index 650193f0e26d..d1b0abcf47bb 100644 --- a/packages/expect/src/__tests__/toThrowMatchers.test.ts +++ b/packages/expect/src/__tests__/toThrowMatchers.test.ts @@ -231,9 +231,7 @@ matchers.forEach(toThrow => { // Received message in report if object has message property. class ErrorMessage { // not extending Error! - constructor(message) { - this.message = message; - } + constructor(public message: string) {} } const expected = new ErrorMessage('apple'); diff --git a/packages/jest-circus/README.md b/packages/jest-circus/README.md index 67305ed4a04a..75a2f771d23d 100644 --- a/packages/jest-circus/README.md +++ b/packages/jest-circus/README.md @@ -15,7 +15,7 @@ Circus allows you to bind to events via an optional event handler on any [custom ```js import {Event, State} from 'jest-circus'; -import NodeEnvironment from 'jest-environment-node'; +import {TestEnvironment as NodeEnvironment} from 'jest-environment-node'; class MyCustomEnvironment extends NodeEnvironment { //... diff --git a/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts b/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts index 65322ba71184..86c951ae48cc 100644 --- a/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts +++ b/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts @@ -26,6 +26,7 @@ describe('test/it.failing error throwing', () => { }); it('it throws error with missing callback function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusIt.failing('test2'); }).toThrowError( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', @@ -33,6 +34,7 @@ describe('test/it.failing error throwing', () => { }); it("it throws an error when first argument isn't valid", () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusIt.failing(() => {}); }).toThrowError( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', @@ -40,6 +42,7 @@ describe('test/it.failing error throwing', () => { }); it('it throws an error when callback function is not a function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusIt.failing('test4', 'test4b'); }).toThrowError( 'Invalid second argument, test4b. It must be a callback function.', @@ -47,6 +50,7 @@ describe('test/it.failing error throwing', () => { }); it('test throws error with missing callback function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusTest.failing('test5'); }).toThrowError( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', @@ -54,6 +58,7 @@ describe('test/it.failing error throwing', () => { }); it("test throws an error when first argument isn't a string", () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusTest.failing(() => {}); }).toThrowError( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', @@ -61,6 +66,7 @@ describe('test/it.failing error throwing', () => { }); it('test throws an error when callback function is not a function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusTest.failing('test7', 'test8b'); }).toThrowError( 'Invalid second argument, test8b. It must be a callback function.', diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts index b783b7b3069a..bcdc4ea1169e 100644 --- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts +++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts @@ -28,12 +28,12 @@ describe('test/it.todo error throwing', () => { }); it('todo throws error when given more than one argument', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here circusIt.todo('test1', () => {}); }).toThrowError('Todo must be called with only a description.'); }); it('todo throws error when given none string description', () => { expect(() => { - // @ts-expect-error: Testing runtime errors here circusIt.todo(() => {}); }).toThrowError('Todo must be called with only a description.'); }); diff --git a/packages/jest-circus/src/__tests__/hooksError.test.ts b/packages/jest-circus/src/__tests__/hooksError.test.ts index 7781d7604123..789aab96563b 100644 --- a/packages/jest-circus/src/__tests__/hooksError.test.ts +++ b/packages/jest-circus/src/__tests__/hooksError.test.ts @@ -5,30 +5,33 @@ * LICENSE file in the root directory of this source tree. */ -import {Circus} from '@jest/types'; +import type {Circus} from '@jest/types'; import circus from '../'; -describe.each(['beforeEach', 'beforeAll', 'afterEach', 'afterAll'])( - '%s hooks error throwing', - (fn: Circus.HookType) => { - test.each([ - ['String'], - [1], - [[]], - [{}], - [Symbol('hello')], - [true], - [null], - [undefined], - ])( - `${fn} throws an error when %p is provided as a first argument to it`, - el => { - expect(() => { - circus[fn](el); - }).toThrowError( - 'Invalid first argument. It must be a callback function.', - ); - }, - ); - }, -); +describe.each([ + 'beforeEach', + 'beforeAll', + 'afterEach', + 'afterAll', +] as Array)('%s hooks error throwing', fn => { + test.each([ + ['String'], + [1], + [[]], + [{}], + [Symbol('hello')], + [true], + [null], + [undefined], + ])( + `${fn} throws an error when %p is provided as a first argument to it`, + el => { + expect(() => { + // @ts-expect-error: Testing runtime errors here + circus[fn](el); + }).toThrowError( + 'Invalid first argument. It must be a callback function.', + ); + }, + ); +}); diff --git a/packages/jest-cli/src/__tests__/cli/args.test.ts b/packages/jest-cli/src/__tests__/cli/args.test.ts index 89593f889ebd..539a9a18c21e 100644 --- a/packages/jest-cli/src/__tests__/cli/args.test.ts +++ b/packages/jest-cli/src/__tests__/cli/args.test.ts @@ -105,7 +105,6 @@ describe('check', () => { describe('buildArgv', () => { it('should return only camelcased args ', async () => { const mockProcessArgv = jest - // @ts-expect-error .spyOn(process.argv, 'slice') .mockImplementation(() => ['--clear-mocks']); diff --git a/packages/jest-cli/src/init/__tests__/init.test.js b/packages/jest-cli/src/init/__tests__/init.test.js index 6f8867a246b8..ccf4cc52e1ab 100644 --- a/packages/jest-cli/src/init/__tests__/init.test.js +++ b/packages/jest-cli/src/init/__tests__/init.test.js @@ -7,7 +7,7 @@ /* eslint-disable no-eval */ import * as path from 'path'; -import * as fs from 'graceful-fs'; +import fs from 'graceful-fs'; import prompts from 'prompts'; import {constants} from 'jest-config'; import init from '../'; diff --git a/packages/jest-config/src/__tests__/normalize.test.ts b/packages/jest-config/src/__tests__/normalize.test.ts index 8f2956fad502..f8bfa76cd0da 100644 --- a/packages/jest-config/src/__tests__/normalize.test.ts +++ b/packages/jest-config/src/__tests__/normalize.test.ts @@ -7,20 +7,20 @@ */ import {createHash} from 'crypto'; -import path from 'path'; +import * as path from 'path'; import semver = require('semver'); import type {Config} from '@jest/types'; import {escapeStrForRegex} from 'jest-regex-util'; import Defaults from '../Defaults'; import {DEFAULT_JS_PATTERN} from '../constants'; -import normalize from '../normalize'; +import normalize, {AllOptions} from '../normalize'; const DEFAULT_CSS_PATTERN = '\\.(css)$'; jest - .mock('path', () => jest.requireActual('path').posix) + .mock('path', () => jest.requireActual('path').posix) .mock('graceful-fs', () => { - const realFs = jest.requireActual('fs'); + const realFs = jest.requireActual('fs'); return { ...realFs, @@ -35,7 +35,9 @@ let expectedPathAbs: string; let expectedPathAbsAnother: string; let virtualModuleRegexes: Array; -beforeEach(() => (virtualModuleRegexes = [/jest-circus/, /babel-jest/])); +beforeEach(() => { + virtualModuleRegexes = [/jest-circus/, /babel-jest/]; +}); const findNodeModule = jest.fn(name => { if (virtualModuleRegexes.some(regex => regex.test(name))) { return name; @@ -211,7 +213,7 @@ describe('findRelatedTests', () => { }); }); -function testPathArray(key: string) { +function testPathArray(key: keyof AllOptions) { it('normalizes all paths relative to rootDir', async () => { const {options} = await normalize( { @@ -1612,7 +1614,10 @@ describe('testPathPattern', () => { describe('win32', () => { beforeEach(() => { - jest.mock('path', () => jest.requireActual('path').win32); + jest.mock( + 'path', + () => jest.requireActual('path').win32, + ); require('jest-resolve').default.findNodeModule = findNodeModule; }); diff --git a/packages/jest-config/src/__tests__/readConfigs.test.ts b/packages/jest-config/src/__tests__/readConfigs.test.ts index bdd76850552a..e6622d699f9b 100644 --- a/packages/jest-config/src/__tests__/readConfigs.test.ts +++ b/packages/jest-config/src/__tests__/readConfigs.test.ts @@ -7,7 +7,7 @@ import {readConfigs} from '../index'; jest.mock('graceful-fs', () => ({ - ...jest.requireActual('fs'), + ...jest.requireActual('fs'), existsSync: jest.fn(() => true), lstatSync: jest.fn(() => ({ isDirectory: () => false, diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index b069b8a876d5..1a3adee53052 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -52,7 +52,7 @@ const ERROR = `${BULLET}Validation Error`; const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs']; const PRESET_NAME = 'jest-preset'; -type AllOptions = Config.ProjectConfig & Config.GlobalConfig; +export type AllOptions = Config.ProjectConfig & Config.GlobalConfig; const createConfigError = (message: string) => new ValidationError(ERROR, message, DOCUMENTATION_NOTE); diff --git a/packages/jest-core/src/__tests__/SearchSource.test.ts b/packages/jest-core/src/__tests__/SearchSource.test.ts index 7e4af257a870..6780981a2532 100644 --- a/packages/jest-core/src/__tests__/SearchSource.test.ts +++ b/packages/jest-core/src/__tests__/SearchSource.test.ts @@ -11,14 +11,14 @@ import type {Test} from '@jest/test-result'; import type {Config} from '@jest/types'; import {normalize} from 'jest-config'; import Runtime from 'jest-runtime'; -import SearchSource, {SearchResult} from '../SearchSource'; +import SearchSource from '../SearchSource'; jest.setTimeout(15000); jest.mock('graceful-fs', () => { - const realFs = jest.requireActual('fs'); + const realFs = jest.requireActual('fs'); - return { + const mockedFs: typeof import('fs') = { ...realFs, statSync: path => { if (path === '/foo/bar/prefix') { @@ -28,6 +28,8 @@ jest.mock('graceful-fs', () => { return realFs.statSync(path); }, }; + + return mockedFs; }); const rootDir = path.resolve(__dirname, 'test_root'); @@ -53,7 +55,7 @@ const initSearchSource = async ( .spyOn(context.hasteFS, 'getAllFiles') .mockReturnValue(options.contextFiles); } - return new SearchSource(context); + return {config, searchSource: new SearchSource(context)}; }; describe('SearchSource', () => { @@ -62,11 +64,11 @@ describe('SearchSource', () => { describe('isTestFilePath', () => { beforeEach(async () => { - searchSource = await initSearchSource({ + ({searchSource} = await initSearchSource({ id, rootDir: '.', roots: [], - }); + })); }); // micromatch doesn't support '..' through the globstar ('**') to avoid @@ -75,7 +77,7 @@ describe('SearchSource', () => { if (process.platform === 'win32') { return; } - const searchSource = await initSearchSource({ + const {searchSource} = await initSearchSource({ id, rootDir: '.', roots: [], @@ -104,8 +106,9 @@ describe('SearchSource', () => { describe('getTestPaths', () => { const getTestPaths = async (initialOptions: Config.InitialOptions) => { - const searchSource = await initSearchSource(initialOptions); + const {searchSource, config} = await initSearchSource(initialOptions); const {tests: paths} = await searchSource.getTestPaths({ + ...config, testPathPattern: '', }); return paths.map(({path: p}) => path.relative(rootDir, p)).sort(); @@ -292,7 +295,7 @@ describe('SearchSource', () => { describe('filterPathsWin32', () => { beforeEach(async () => { - searchSource = await initSearchSource( + ({searchSource} = await initSearchSource( { id, rootDir: '.', @@ -307,7 +310,7 @@ describe('SearchSource', () => { path.resolve('packages/programs (x86)/my-program.ts'), ], }, - ); + )); }); it('should allow a simple match', async () => { @@ -372,7 +375,7 @@ describe('SearchSource', () => { const rootPath = path.join(rootDir, 'root.js'); beforeEach(async () => { - searchSource = await initSearchSource({ + ({searchSource} = await initSearchSource({ haste: { hasteImplModulePath: path.join( __dirname, @@ -387,7 +390,7 @@ describe('SearchSource', () => { }, id: 'SearchSource-findRelatedTests-tests', rootDir, - }); + })); }); it('makes sure a file is related to itself', async () => { @@ -431,12 +434,12 @@ describe('SearchSource', () => { describe('findRelatedTestsFromPattern', () => { beforeEach(async () => { - searchSource = await initSearchSource({ + ({searchSource} = await initSearchSource({ id, moduleFileExtensions: ['js', 'jsx', 'foobar'], rootDir, testMatch, - }); + })); }); it('returns empty search result for empty input', async () => { @@ -483,11 +486,11 @@ describe('SearchSource', () => { if (process.platform === 'win32') { return; } - searchSource = await initSearchSource({ + ({searchSource} = await initSearchSource({ id, rootDir: '.', roots: ['/foo/bar/prefix'], - }); + })); const input = ['/foo/bar/prefix-suffix/__tests__/my-test.test.js']; const data = searchSource.findTestsByPaths(input); @@ -502,7 +505,7 @@ describe('SearchSource', () => { ); beforeEach(async () => { - searchSource = await initSearchSource({ + ({searchSource} = await initSearchSource({ haste: { hasteImplModulePath: path.resolve( __dirname, @@ -511,7 +514,7 @@ describe('SearchSource', () => { }, id: 'SearchSource-findRelatedSourcesFromTestsInChangedFiles-tests', rootDir, - }); + })); }); it('return empty set if no SCM', async () => { diff --git a/packages/jest-core/src/__tests__/collectHandles.test.js b/packages/jest-core/src/__tests__/collectHandles.test.js index 9b79c5e6e280..229ccb9a2c7a 100644 --- a/packages/jest-core/src/__tests__/collectHandles.test.js +++ b/packages/jest-core/src/__tests__/collectHandles.test.js @@ -6,7 +6,7 @@ * */ -import crypto from 'crypto'; +import * as crypto from 'crypto'; import {promises as dns} from 'dns'; import http from 'http'; import {PerformanceObserver} from 'perf_hooks'; diff --git a/packages/jest-core/src/__tests__/getNoTestsFoundMessage.test.ts b/packages/jest-core/src/__tests__/getNoTestsFoundMessage.test.ts index 259e46b7d66e..7de432085d2f 100644 --- a/packages/jest-core/src/__tests__/getNoTestsFoundMessage.test.ts +++ b/packages/jest-core/src/__tests__/getNoTestsFoundMessage.test.ts @@ -10,7 +10,7 @@ import type {Config} from '@jest/types'; import getNoTestsFoundMessage from '../getNoTestsFoundMessage'; jest.mock('jest-util', () => ({ - ...jest.requireActual('jest-util'), + ...jest.requireActual('jest-util'), isInteractive: true, })); diff --git a/packages/jest-core/src/__tests__/watchFileChanges.test.ts b/packages/jest-core/src/__tests__/watchFileChanges.test.ts index 2f736b547d02..ed5a63821d72 100644 --- a/packages/jest-core/src/__tests__/watchFileChanges.test.ts +++ b/packages/jest-core/src/__tests__/watchFileChanges.test.ts @@ -11,7 +11,7 @@ import * as path from 'path'; import * as fs from 'graceful-fs'; import type {AggregatedResult} from '@jest/test-result'; import {normalize} from 'jest-config'; -import type HasteMap from 'jest-haste-map'; +import type {IHasteMap} from 'jest-haste-map'; import Runtime from 'jest-runtime'; import {interopRequireDefault} from 'jest-util'; import {JestHook} from 'jest-watcher'; @@ -19,8 +19,8 @@ import {JestHook} from 'jest-watcher'; describe('Watch mode flows with changed files', () => { jest.resetModules(); - let watch: unknown; - let pipe: NodeJS.ReadStream; + let watch: typeof import('../watch').default; + let pipe: NodeJS.WriteStream; let stdin: MockStdin; const testDirectory = path.resolve(tmpdir(), 'jest-tmp'); const fileTargetPath = path.resolve(testDirectory, 'lost-file.js'); @@ -29,7 +29,7 @@ describe('Watch mode flows with changed files', () => { 'watch-test-fake.test.js', ); const cacheDirectory = path.resolve(tmpdir(), `tmp${Math.random()}`); - let hasteMapInstance: HasteMap; + let hasteMapInstance: IHasteMap; beforeEach(() => { watch = interopRequireDefault(require('../watch')).default; diff --git a/packages/jest-diff/src/__tests__/diff.test.ts b/packages/jest-diff/src/__tests__/diff.test.ts index 7fd124b965d5..a95320c0a344 100644 --- a/packages/jest-diff/src/__tests__/diff.test.ts +++ b/packages/jest-diff/src/__tests__/diff.test.ts @@ -13,7 +13,7 @@ import {NO_DIFF_MESSAGE} from '../constants'; import {diffLinesUnified, diffLinesUnified2} from '../diffLines'; import {noColor} from '../normalizeDiffOptions'; import {diffStringsUnified} from '../printDiffs'; -import {DiffOptions} from '../types'; +import type {DiffOptions} from '../types'; const optionsCounts: DiffOptions = { includeChangeCounts: true, @@ -1077,7 +1077,8 @@ describe('options', () => { }); test('diff middle dot', () => { - const replaceSpacesWithMiddleDot = string => '·'.repeat(string.length); + const replaceSpacesWithMiddleDot = (string: string) => + '·'.repeat(string.length); const options = { changeLineTrailingSpaceColor: replaceSpacesWithMiddleDot, commonLineTrailingSpaceColor: replaceSpacesWithMiddleDot, diff --git a/packages/jest-each/src/__tests__/array.test.ts b/packages/jest-each/src/__tests__/array.test.ts index b89e31f49d32..d76260f5c7df 100644 --- a/packages/jest-each/src/__tests__/array.test.ts +++ b/packages/jest-each/src/__tests__/array.test.ts @@ -12,7 +12,7 @@ import each from '../'; const noop = () => {}; const expectFunction = expect.any(Function); -const get = (object, lensPath) => +const get = (object: T, lensPath: Array): T => lensPath.reduce((acc, key) => acc[key], object); const getGlobalTestMocks = () => { diff --git a/packages/jest-each/src/__tests__/template.test.ts b/packages/jest-each/src/__tests__/template.test.ts index f39031840f93..193800374c31 100644 --- a/packages/jest-each/src/__tests__/template.test.ts +++ b/packages/jest-each/src/__tests__/template.test.ts @@ -6,36 +6,41 @@ * */ +import type {Global} from '@jest/types'; import each from '../'; const noop = () => {}; const expectFunction = expect.any(Function); -const get = (object, lensPath) => +const get = ( + object: T, + lensPath: Array, +): ((...args: Array) => unknown) => lensPath.reduce((acc, key) => acc[key], object); -const getGlobalTestMocks = () => { - const globals: any = { - describe: jest.fn(), - fdescribe: jest.fn(), - fit: jest.fn(), - it: jest.fn(), - test: jest.fn(), - xdescribe: jest.fn(), - xit: jest.fn(), - xtest: jest.fn(), +const getGlobalTestMocks = + (): jest.MockedObject => { + const globals: any = { + describe: jest.fn(), + fdescribe: jest.fn(), + fit: jest.fn(), + it: jest.fn(), + test: jest.fn(), + xdescribe: jest.fn(), + xit: jest.fn(), + xtest: jest.fn(), + }; + globals.test.only = jest.fn(); + globals.test.skip = jest.fn(); + globals.test.concurrent = jest.fn(); + globals.test.concurrent.only = jest.fn(); + globals.test.concurrent.skip = jest.fn(); + globals.it.only = jest.fn(); + globals.it.skip = jest.fn(); + globals.describe.only = jest.fn(); + globals.describe.skip = jest.fn(); + return globals; }; - globals.test.only = jest.fn(); - globals.test.skip = jest.fn(); - globals.test.concurrent = jest.fn(); - globals.test.concurrent.only = jest.fn(); - globals.test.concurrent.skip = jest.fn(); - globals.it.only = jest.fn(); - globals.it.skip = jest.fn(); - globals.describe.only = jest.fn(); - globals.describe.skip = jest.fn(); - return globals; -}; describe('jest-each', () => { [ @@ -65,7 +70,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -82,7 +87,9 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => + jest.mocked(globalMock).mock.calls[0][1](), + ).not.toThrowError(); expect(testCallBack).toHaveBeenCalledWith({ b: 1, expected: 2, @@ -103,7 +110,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -120,7 +127,9 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => + jest.mocked(globalMock).mock.calls[0][1](), + ).not.toThrowError(); expect(testCallBack).toHaveBeenCalledWith({ a: 1, expected: 2, @@ -141,7 +150,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -158,7 +167,9 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => + jest.mocked(globalMock).mock.calls[0][1](), + ).not.toThrowError(); expect(testCallBack).toHaveBeenCalledWith({ '(๑ఠ‿ఠ๑)<expected': 2, a: 1, @@ -241,7 +252,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -259,7 +270,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -278,7 +289,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -293,7 +304,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); expect(() => - globalMock.mock.calls[0][1](), + jest.mocked(globalMock).mock.calls[0][1](), ).toThrowErrorMatchingSnapshot(); expect(testCallBack).not.toHaveBeenCalled(); }); @@ -443,11 +454,11 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - globalMock.mock.calls[0][1](); + jest.mocked(globalMock).mock.calls[0][1](); expect(testCallBack).toHaveBeenCalledTimes(1); expect(testCallBack).toHaveBeenCalledWith({a: 0, b: 1, expected: 1}); - globalMock.mock.calls[1][1](); + jest.mocked(globalMock).mock.calls[1][1](); expect(testCallBack).toHaveBeenCalledTimes(2); expect(testCallBack).toHaveBeenCalledWith({a: 1, b: 1, expected: 2}); }); diff --git a/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts b/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts index f9480b63dff2..6f260036c794 100644 --- a/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts +++ b/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts @@ -287,7 +287,7 @@ describe('FakeTimers', () => { }); it('cancels a callback even from native nextTick', () => { - const nativeNextTick = jest.fn(); + const nativeNextTick = jest.fn(); const global = { process: { @@ -316,7 +316,7 @@ describe('FakeTimers', () => { }); it('cancels a callback even from native setImmediate', () => { - const nativeSetImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); const global = { process, @@ -343,7 +343,7 @@ describe('FakeTimers', () => { }); it('doesnt run a tick callback if native nextTick already did', () => { - const nativeNextTick = jest.fn(); + const nativeNextTick = jest.fn(); const global = { process: { @@ -372,7 +372,7 @@ describe('FakeTimers', () => { }); it('doesnt run immediate if native setImmediate already did', () => { - const nativeSetImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); const global = { process, @@ -400,7 +400,7 @@ describe('FakeTimers', () => { }); it('native doesnt run immediate if fake already did', () => { - const nativeSetImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); const global = { process, @@ -508,7 +508,7 @@ describe('FakeTimers', () => { }); it('warns when trying to advance timers while real timers are used', () => { - const mockConsole = {warn: jest.fn()}; + const mockConsole = {warn: jest.fn()}; const timers = new FakeTimers({ config: { rootDir: __dirname, @@ -1027,7 +1027,7 @@ describe('FakeTimers', () => { describe('runOnlyPendingTimers', () => { it('runs all timers in order', () => { - const nativeSetImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); const global = { cancelAnimationFrame: () => {}, @@ -1329,8 +1329,8 @@ describe('FakeTimers', () => { }); it('resets native setImmediate when present', () => { - const nativeSetImmediate = jest.fn(); - const nativeClearImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); + const nativeClearImmediate = jest.fn(); const global = { clearImmediate: nativeClearImmediate, @@ -1448,8 +1448,8 @@ describe('FakeTimers', () => { }); it('resets mock setImmediate when present', () => { - const nativeSetImmediate = jest.fn(); - const nativeClearImmediate = jest.fn(); + const nativeSetImmediate = jest.fn(); + const nativeClearImmediate = jest.fn(); const global = { clearImmediate: nativeClearImmediate, diff --git a/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts b/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts index ffc6bb8c8a74..779e48fc9c3f 100644 --- a/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts +++ b/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts @@ -119,7 +119,7 @@ describe('FakeTimers', () => { const timers = new FakeTimers({config: makeProjectConfig(), global}); timers.useFakeTimers(); - const runOrder = []; + const runOrder: Array = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); @@ -218,7 +218,7 @@ describe('FakeTimers', () => { const timers = new FakeTimers({config: makeProjectConfig(), global}); timers.useFakeTimers(); - const runOrder = []; + const runOrder: Array = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); const mock3 = jest.fn(() => runOrder.push('mock3')); @@ -248,17 +248,20 @@ describe('FakeTimers', () => { }); it('warns when trying to advance timers while real timers are used', () => { - const consoleWarn = console.warn; - console.warn = jest.fn(); + const consoleWarnSpy = jest + .spyOn(console, 'warn') + .mockImplementation(() => { + // nothing + }); const timers = new FakeTimers({ config: makeProjectConfig({rootDir: __dirname}), global: globalThis, }); timers.runAllTimers(); expect( - console.warn.mock.calls[0][0].split('\nStack Trace')[0], + consoleWarnSpy.mock.calls[0][0].split('\nStack Trace')[0], ).toMatchSnapshot(); - console.warn = consoleWarn; + consoleWarnSpy.mockRestore(); timers.useRealTimers(); }); @@ -397,7 +400,7 @@ describe('FakeTimers', () => { const timers = new FakeTimers({config: makeProjectConfig(), global}); timers.useFakeTimers(); - const runOrder = []; + const runOrder: Array = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); const mock3 = jest.fn(() => runOrder.push('mock3')); @@ -663,7 +666,7 @@ describe('FakeTimers', () => { const timers = new FakeTimers({config: makeProjectConfig(), global}); timers.useFakeTimers(); - const runOrder = []; + const runOrder: Array = []; global.setTimeout(function cb() { runOrder.push('mock1'); diff --git a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js index 9970b1c4f645..7afe3edd69d4 100644 --- a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js +++ b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js @@ -7,7 +7,7 @@ */ 'use strict'; -import path from 'path'; +import * as path from 'path'; import getMockName from '../getMockName'; describe('getMockName', () => { diff --git a/packages/jest-haste-map/src/__tests__/includes_dotfiles.test.ts b/packages/jest-haste-map/src/__tests__/includes_dotfiles.test.ts index 64bf2257d0ab..d05545f1f0b4 100644 --- a/packages/jest-haste-map/src/__tests__/includes_dotfiles.test.ts +++ b/packages/jest-haste-map/src/__tests__/includes_dotfiles.test.ts @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; +import * as path from 'path'; import HasteMap from '../index'; const rootDir = path.join(__dirname, './test_dotfiles_root'); diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index a3b2c6efc923..c88cfd1d196f 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -6,7 +6,7 @@ * */ -import crypto from 'crypto'; +import * as crypto from 'crypto'; import * as path from 'path'; function mockHashContents(contents) { diff --git a/packages/jest-haste-map/src/__tests__/worker.test.js b/packages/jest-haste-map/src/__tests__/worker.test.js index 601ef162af68..441f10ae659e 100644 --- a/packages/jest-haste-map/src/__tests__/worker.test.js +++ b/packages/jest-haste-map/src/__tests__/worker.test.js @@ -9,7 +9,7 @@ 'use strict'; import * as path from 'path'; -import * as fs from 'graceful-fs'; +import fs from 'graceful-fs'; import H from '../constants'; import {getSha1, worker} from '../worker'; diff --git a/packages/jest-haste-map/src/lib/__tests__/fast_path.test.js b/packages/jest-haste-map/src/lib/__tests__/fast_path.test.js index 454500a823df..6fb59169762a 100644 --- a/packages/jest-haste-map/src/lib/__tests__/fast_path.test.js +++ b/packages/jest-haste-map/src/lib/__tests__/fast_path.test.js @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; +import * as path from 'path'; import {relative, resolve} from '../fast_path'; describe('fastPath.relative', () => { diff --git a/packages/jest-haste-map/src/watchers/WatchmanWatcher.js b/packages/jest-haste-map/src/watchers/WatchmanWatcher.js index 69ef94afaf0f..c1db66de7c08 100644 --- a/packages/jest-haste-map/src/watchers/WatchmanWatcher.js +++ b/packages/jest-haste-map/src/watchers/WatchmanWatcher.js @@ -5,11 +5,11 @@ * LICENSE file in the root directory of this source tree. */ -import assert from 'assert'; +import * as assert from 'assert'; import {EventEmitter} from 'events'; -import path from 'path'; +import * as path from 'path'; import watchman from 'fb-watchman'; -import * as fs from 'graceful-fs'; +import fs from 'graceful-fs'; import RecrawlWarning from './RecrawlWarning'; import common from './common'; diff --git a/packages/jest-jasmine2/src/__tests__/Suite.test.ts b/packages/jest-jasmine2/src/__tests__/Suite.test.ts index caf44ac93ffa..0dd867232d0e 100644 --- a/packages/jest-jasmine2/src/__tests__/Suite.test.ts +++ b/packages/jest-jasmine2/src/__tests__/Suite.test.ts @@ -19,7 +19,7 @@ describe('Suite', () => { it("doesn't throw on addExpectationResult when there are no children", () => { expect(() => { - // @ts-expect-error + // @ts-expect-error: Testing runtime errors here suite.addExpectationResult(); }).not.toThrow(); }); diff --git a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts index 13b80219ceeb..9125f58df3f5 100644 --- a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts @@ -8,27 +8,29 @@ export type SharedHookType = 'afterAll' | 'beforeAll'; export type HookType = SharedHookType | 'afterEach' | 'beforeEach'; -describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( - '%s hooks error throwing', - (fn: HookType) => { - test.each([ - ['String'], - [1], - [[]], - [{}], - [Symbol('hello')], - [true], - [null], - [undefined], - ])( - `${fn} throws an error when %p is provided as a first argument to it`, - el => { - expect(() => { - globalThis[fn](el); - }).toThrowError( - 'Invalid first argument. It must be a callback function.', - ); - }, - ); - }, -); +describe.each([ + 'beforeEach', + 'beforeAll', + 'afterEach', + 'afterAll', +] as Array)('%s hooks error throwing', fn => { + test.each([ + ['String'], + [1], + [[]], + [{}], + [Symbol('hello')], + [true], + [null], + [undefined], + ])( + `${fn} throws an error when %p is provided as a first argument to it`, + el => { + expect(() => { + globalThis[fn](el); + }).toThrowError( + 'Invalid first argument. It must be a callback function.', + ); + }, + ); +}); diff --git a/packages/jest-jasmine2/src/__tests__/itTestError.test.ts b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts index 24ad11cea344..c4ec10d5ca09 100644 --- a/packages/jest-jasmine2/src/__tests__/itTestError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts @@ -9,6 +9,7 @@ describe('test/it error throwing', () => { it('it throws error with missing callback function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here it('test1'); }).toThrowError( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', @@ -16,7 +17,7 @@ describe('test/it error throwing', () => { }); it("it throws an error when first argument isn't valid", () => { expect(() => { - // @ts-expect-error + // @ts-expect-error: Testing runtime errors here it(() => {}); }).toThrowError( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', @@ -24,7 +25,7 @@ describe('test/it error throwing', () => { }); it('it throws an error when callback function is not a function', () => { expect(() => { - // @ts-expect-error + // @ts-expect-error: Testing runtime errors here it('test3', 'test3b'); }).toThrowError( 'Invalid second argument, test3b. It must be a callback function.', @@ -32,6 +33,7 @@ describe('test/it error throwing', () => { }); test('test throws error with missing callback function', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here test('test4'); }).toThrowError( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', @@ -39,7 +41,7 @@ describe('test/it error throwing', () => { }); test("test throws an error when first argument isn't valid", () => { expect(() => { - // @ts-expect-error + // @ts-expect-error: Testing runtime errors here test(() => {}); }).toThrowError( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', @@ -47,7 +49,7 @@ describe('test/it error throwing', () => { }); test('test throws an error when callback function is not a function', () => { expect(() => { - // @ts-expect-error + // @ts-expect-error: Testing runtime errors here test('test6', 'test6b'); }).toThrowError( 'Invalid second argument, test6b. It must be a callback function.', diff --git a/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts index 9cbf1570dac4..50a00962ff2f 100644 --- a/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts +++ b/packages/jest-jasmine2/src/__tests__/queueRunner.test.ts @@ -6,27 +6,21 @@ * */ -import queueRunner from '../queueRunner'; +import queueRunner, {Options, QueueableFn} from '../queueRunner'; describe('queueRunner', () => { it('runs every function in the queue.', async () => { const fnOne = jest.fn(next => next()); const fnTwo = jest.fn(next => next()); - const options = { + const options: Options = { clearTimeout, - fail: () => {}, - onException: () => {}, - queueableFns: [ - { - fn: fnOne, - }, - { - fn: fnTwo, - }, - ], + fail: jest.fn(), + onException: jest.fn(), + queueableFns: [{fn: fnOne}, {fn: fnTwo}], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(fnTwo).toHaveBeenCalled(); @@ -36,21 +30,15 @@ describe('queueRunner', () => { const fail = jest.fn(); const fnOne = jest.fn(next => next.fail()); const fnTwo = jest.fn(next => next()); - const options = { + const options: Options = { clearTimeout, fail, - onException: () => {}, - queueableFns: [ - { - fn: fnOne, - }, - { - fn: fnTwo, - }, - ], + onException: jest.fn(), + queueableFns: [{fn: fnOne}, {fn: fnTwo}], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(fail).toHaveBeenCalled(); @@ -65,21 +53,15 @@ describe('queueRunner', () => { }); const fnTwo = jest.fn(next => next()); const onException = jest.fn(); - const options = { + const options: Options = { clearTimeout, - fail: () => {}, + fail: jest.fn(), onException, - queueableFns: [ - { - fn: fnOne, - }, - { - fn: fnTwo, - }, - ], + queueableFns: [{fn: fnOne}, {fn: fnTwo}], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(onException).toHaveBeenCalledWith(error); @@ -88,12 +70,12 @@ describe('queueRunner', () => { }); it('passes an error to `onException` on timeout.', async () => { - const fnOne = jest.fn(_next => {}); - const fnTwo = jest.fn(next => next()); - const onException = jest.fn(); - const options = { + const fnOne = jest.fn(_next => {}); + const fnTwo = jest.fn(next => next()); + const onException = jest.fn<(error: Error) => void>(); + const options: Options = { clearTimeout, - fail: () => {}, + fail: jest.fn(), onException, queueableFns: [ { @@ -101,13 +83,12 @@ describe('queueRunner', () => { // It times out in zero seconds. timeout: () => 0, }, - { - fn: fnTwo, - }, + {fn: fnTwo}, ], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + await queueRunner(options); expect(fnOne).toHaveBeenCalled(); expect(onException).toHaveBeenCalled(); @@ -121,13 +102,15 @@ describe('queueRunner', () => { it('calls `fail` with arguments', async () => { const failFn = jest.fn(next => next.fail('miserably', 'failed')); - const options = { + const options: Options = { clearTimeout, fail: jest.fn(), + onException: jest.fn(), queueableFns: [{fn: failFn}], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + await queueRunner(options); expect(options.fail).toHaveBeenCalledWith('miserably', 'failed'); @@ -138,21 +121,15 @@ describe('queueRunner', () => { const fail = jest.fn(); const fnOne = jest.fn(next => next(error)); const fnTwo = jest.fn(next => next()); - const options = { + const options: Options = { clearTimeout, fail, - onException: () => {}, - queueableFns: [ - { - fn: fnOne, - }, - { - fn: fnTwo, - }, - ], + onException: jest.fn(), + queueableFns: [{fn: fnOne}, {fn: fnTwo}], setTimeout, + userContext: {} as any, }; - // @ts-expect-error + 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 88b79073d469..598c3630ae06 100644 --- a/packages/jest-jasmine2/src/__tests__/reporter.test.ts +++ b/packages/jest-jasmine2/src/__tests__/reporter.test.ts @@ -6,8 +6,8 @@ * */ -import {SpecResult} from '../jasmine/Spec'; -import {SuiteResult} from '../jasmine/Suite'; +import type {SpecResult} from '../jasmine/Spec'; +import type {SuiteResult} from '../jasmine/Suite'; import JasmineReporter from '../reporter'; describe('Jasmine2Reporter', () => { @@ -24,7 +24,7 @@ describe('Jasmine2Reporter', () => { description: 'description', failedExpectations: [], fullName: name, - } as SpecResult); + } as any as SpecResult); reporter.suiteStarted({description: 'parent'} as SuiteResult); reporter.suiteStarted({description: 'child'} as SuiteResult); reporter.specDone(makeSpec('spec 1')); diff --git a/packages/jest-jasmine2/src/__tests__/todoError.test.ts b/packages/jest-jasmine2/src/__tests__/todoError.test.ts index aab30f522aca..cd875cfbefb8 100644 --- a/packages/jest-jasmine2/src/__tests__/todoError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/todoError.test.ts @@ -15,12 +15,12 @@ describe('test/it.todo error throwing', () => { }); it('it throws error when given more than one argument', () => { expect(() => { + // @ts-expect-error: Testing runtime errors here it.todo('test1', () => {}); }).toThrowError('Todo must be called with only a description.'); }); it('it throws error when given none string description', () => { expect(() => { - // @ts-expect-error it.todo(() => {}); }).toThrowError('Todo must be called with only a description.'); }); diff --git a/packages/jest-leak-detector/src/__tests__/index.test.ts b/packages/jest-leak-detector/src/__tests__/index.test.ts index 795ab6bc24c5..c6ad784d3b08 100644 --- a/packages/jest-leak-detector/src/__tests__/index.test.ts +++ b/packages/jest-leak-detector/src/__tests__/index.test.ts @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -'use strict'; - import LeakDetector from '../index'; const gc = globalThis.gc; diff --git a/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts b/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts index c5040d69b3ac..1f2391c8d4ba 100644 --- a/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts @@ -39,7 +39,8 @@ describe('Replaceable', () => { test('init with other type should throw error', () => { expect(() => { - const replaceable = new Replaceable(new Date()); + // eslint-disable-next-line no-new + new Replaceable(new Date()); }).toThrow('Type date is not support in Replaceable!'); }); }); diff --git a/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts b/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts index e09404af8198..86dafb46e094 100644 --- a/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts @@ -206,12 +206,12 @@ describe('printDiffOrStringify', () => { }); test('map', () => { - const expected: Map = new Map([ + const expected = new Map([ ['a', 1], ['b', expect.any(Number)], ['c', 3], ]); - const received: Map = new Map([ + const received = new Map([ ['a', 1], ['b', 2], ['c', 2], @@ -254,13 +254,13 @@ describe('printDiffOrStringify', () => { }); test('circular map', () => { - const expected: Map = new Map([ + const expected = new Map([ ['a', 1], ['b', expect.any(Number)], ['c', 3], ]); expected.set('circular', expected); - const received: Map = new Map([ + const received = new Map([ ['a', 1], ['b', 2], ['c', 2], diff --git a/packages/jest-message-util/src/__tests__/messages.test.ts b/packages/jest-message-util/src/__tests__/messages.test.ts index 03f27a96ad0f..7eeabb8dc159 100644 --- a/packages/jest-message-util/src/__tests__/messages.test.ts +++ b/packages/jest-message-util/src/__tests__/messages.test.ts @@ -19,7 +19,7 @@ import { const rootDir = tempy.directory(); jest.mock('graceful-fs', () => ({ - ...jest.requireActual('fs'), + ...jest.requireActual('fs'), readFileSync: jest.fn(), })); @@ -93,10 +93,14 @@ it('should exclude jasmine from stack trace for Unix paths.', () => { [ { ancestorTitles: [], + duration: undefined, + failureDetails: [], failureMessages: [unixStackTrace], fullName: 'full name', + invocations: undefined, location: null, numPassingAsserts: 0, + retryReasons: undefined, status: 'failed', title: 'Unix test', }, @@ -137,10 +141,14 @@ it('formatStackTrace should strip node internals', () => { [ { ancestorTitles: [], + duration: undefined, + failureDetails: [], failureMessages: [assertionStack], fullName: 'full name', + invocations: undefined, location: null, numPassingAsserts: 0, + retryReasons: undefined, status: 'failed', title: 'Unix test', }, @@ -162,10 +170,14 @@ it('should not exclude vendor from stack trace', () => { [ { ancestorTitles: [], + duration: undefined, + failureDetails: [], failureMessages: [vendorStack], fullName: 'full name', + invocations: undefined, location: null, numPassingAsserts: 0, + retryReasons: undefined, status: 'failed', title: 'Vendor test', }, @@ -187,10 +199,14 @@ it('retains message in babel code frame error', () => { [ { ancestorTitles: [], + duration: undefined, + failureDetails: [], failureMessages: [babelStack], fullName: 'full name', + invocations: undefined, location: null, numPassingAsserts: 0, + retryReasons: undefined, status: 'failed', title: 'Babel test', }, @@ -208,7 +224,9 @@ it('retains message in babel code frame error', () => { }); it('codeframe', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatExecError( { @@ -237,7 +255,9 @@ it('codeframe', () => { }); it('no codeframe', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatExecError( { @@ -266,7 +286,9 @@ it('no codeframe', () => { }); it('no stack', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatExecError( { @@ -297,7 +319,9 @@ it('no stack', () => { describe('formatStackTrace', () => { it('prints code frame and stacktrace', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatStackTrace( ` at Object. (${slash(rootDir)}/file.js:1:7) @@ -322,7 +346,9 @@ describe('formatStackTrace', () => { }); it('does not print code frame when noCodeFrame = true', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatStackTrace( ` at Object. (${slash(rootDir)}/file.js:1:7) @@ -347,7 +373,9 @@ describe('formatStackTrace', () => { }); it('does not print codeframe when noStackTrace = true', () => { - readFileSync.mockImplementationOnce(() => 'throw new Error("Whoops!");'); + jest + .mocked(readFileSync) + .mockImplementationOnce(() => 'throw new Error("Whoops!");'); const message = formatStackTrace( ` at Object. (${slash(rootDir)}/file.js:1:7) @@ -383,5 +411,5 @@ it('getTopFrame should return a path for mjs files', () => { } const frame = getTopFrame(stack); - expect(frame.file).toBe(expectedFile); + expect(frame!.file).toBe(expectedFile); }); diff --git a/packages/jest-mock/src/__tests__/index.test.ts b/packages/jest-mock/src/__tests__/index.test.ts index 27f7ba18369c..ea59ceddd8eb 100644 --- a/packages/jest-mock/src/__tests__/index.test.ts +++ b/packages/jest-mock/src/__tests__/index.test.ts @@ -9,7 +9,7 @@ /* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ import * as util from 'util'; -import vm, {Context} from 'vm'; +import {Context, createContext, runInContext, runInNewContext} from 'vm'; import {ModuleMocker, fn, mocked, spyOn} from '../'; describe('moduleMocker', () => { @@ -18,8 +18,8 @@ describe('moduleMocker', () => { let mockGlobals: typeof globalThis; beforeEach(() => { - mockContext = vm.createContext(); - mockGlobals = vm.runInNewContext('this', mockContext); + mockContext = createContext(); + mockGlobals = runInNewContext('this', mockContext); moduleMocker = new ModuleMocker(mockGlobals); }); @@ -28,11 +28,12 @@ describe('moduleMocker', () => { function x() {} const metadata = moduleMocker.getMetadata(x); expect(x.name).toBe('x'); - expect(metadata.name).toBe('x'); + expect(metadata!.name).toBe('x'); }); it('does not return broken name property', () => { class By { + // @ts-expect-error static name() { return 'this is not a name'; } @@ -285,7 +286,7 @@ describe('moduleMocker', () => { }); it('does not mock methods from Object.prototype (in mock context)', () => { - const Bar = vm.runInContext( + const Bar = runInContext( ` const Foo = { foo() {} }; const Bar = Object.assign(Object.create(Foo), { bar() {} }); @@ -321,7 +322,7 @@ describe('moduleMocker', () => { }); it('does not mock methods from Function.prototype (in mock context)', () => { - const Bar = vm.runInContext( + const Bar = runInContext( ` class Foo {} class Bar extends Foo {} @@ -352,7 +353,7 @@ describe('moduleMocker', () => { }); it('does not mock methods from RegExp.prototype (in mock context)', () => { - const bar = vm.runInContext( + const bar = runInContext( ` const bar = /bar/; bar; diff --git a/packages/jest-repl/src/__tests__/jest_repl.test.js b/packages/jest-repl/src/__tests__/jest_repl.test.js index b86932a89b0e..6d98cd0eeed5 100644 --- a/packages/jest-repl/src/__tests__/jest_repl.test.js +++ b/packages/jest-repl/src/__tests__/jest_repl.test.js @@ -7,7 +7,7 @@ */ import {spawnSync} from 'child_process'; -import path from 'path'; +import * as path from 'path'; const JEST_RUNTIME = require.resolve('../../bin/jest-repl.js'); diff --git a/packages/jest-reporters/src/__tests__/CoverageReporter.test.js b/packages/jest-reporters/src/__tests__/CoverageReporter.test.js index 1b77144cfcdc..be472e400904 100644 --- a/packages/jest-reporters/src/__tests__/CoverageReporter.test.js +++ b/packages/jest-reporters/src/__tests__/CoverageReporter.test.js @@ -22,7 +22,7 @@ let libSourceMaps; let CoverageReporter; let istanbulReports; -import path from 'path'; +import * as path from 'path'; import mock from 'mock-fs'; beforeEach(() => { diff --git a/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts b/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts index ddc81279417f..0a748797cfea 100644 --- a/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts +++ b/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts @@ -8,7 +8,9 @@ import type {Test, TestCaseResult, TestResult} from '@jest/test-result'; import GitHubActionsReporter from '../GitHubActionsReporter'; -process.stderr.write = jest.fn(); +const mockedStderrWrite = jest + .spyOn(process.stderr, 'write') + .mockImplementation(() => true); afterEach(() => { jest.clearAllMocks(); @@ -81,8 +83,8 @@ describe('logs error annotation', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); - expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); + expect(mockedStderrWrite).toBeCalledTimes(1); + expect(mockedStderrWrite.mock.calls[0]).toMatchSnapshot(); }); test('when a test has reference error', () => { @@ -98,8 +100,8 @@ describe('logs error annotation', () => { } as TestResult, ); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); - expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); + expect(mockedStderrWrite).toBeCalledTimes(1); + expect(mockedStderrWrite.mock.calls[0]).toMatchSnapshot(); }); test('when test is wrapped in describe block', () => { @@ -112,8 +114,8 @@ describe('logs error annotation', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); - expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); + expect(mockedStderrWrite).toBeCalledTimes(1); + expect(mockedStderrWrite.mock.calls[0]).toMatchSnapshot(); }); }); @@ -129,7 +131,7 @@ describe('logs warning annotation before logging errors', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(2); - expect(jest.mocked(process.stderr.write).mock.calls).toMatchSnapshot(); + expect(mockedStderrWrite).toBeCalledTimes(2); + expect(mockedStderrWrite.mock.calls).toMatchSnapshot(); }); }); diff --git a/packages/jest-reporters/src/__tests__/generateEmptyCoverage.test.js b/packages/jest-reporters/src/__tests__/generateEmptyCoverage.test.js index 942152dbfab2..8e283c3b8dd7 100644 --- a/packages/jest-reporters/src/__tests__/generateEmptyCoverage.test.js +++ b/packages/jest-reporters/src/__tests__/generateEmptyCoverage.test.js @@ -5,8 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -import os from 'os'; -import path from 'path'; +import * as os from 'os'; +import * as path from 'path'; import istanbulCoverage from 'istanbul-lib-coverage'; import libSourceMaps from 'istanbul-lib-source-maps'; import {makeGlobalConfig, makeProjectConfig} from '@jest/test-utils'; diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index 8d4c2489c7cb..2b6505cef014 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -12,7 +12,7 @@ import {sync as resolveSync} from 'resolve'; import {IModuleMap, ModuleMap} from 'jest-haste-map'; import userResolver from '../__mocks__/userResolver'; import userResolverAsync from '../__mocks__/userResolverAsync'; -import defaultResolver from '../defaultResolver'; +import defaultResolver, {PackageFilter} from '../defaultResolver'; import nodeModulesPaths from '../nodeModulesPaths'; import Resolver from '../resolver'; import type {ResolverConfig} from '../types'; @@ -20,11 +20,14 @@ import type {ResolverConfig} from '../types'; jest.mock('../__mocks__/userResolver').mock('../__mocks__/userResolverAsync'); // Do not fully mock `resolve` because it is used by Jest. Doing it will crash -// in very strange ways. Instead just spy on it and its `sync` method. +// in very strange ways. Instead, just spy on it and its `sync` method. jest.mock('resolve', () => { - const originalModule = jest.requireActual('resolve'); + const originalModule = + jest.requireActual('resolve'); - const m = jest.fn((...args) => originalModule(...args)); + const m = jest.fn((...args) => + originalModule(...args), + ); Object.assign(m, originalModule); m.sync = jest.spyOn(originalModule, 'sync'); @@ -131,7 +134,7 @@ describe('findNodeModule', () => { }); it('wraps passed packageFilter to the resolve module when using the default resolver', () => { - const packageFilter = jest.fn(); + const packageFilter = jest.fn(); // A resolver that delegates to defaultResolver with a packageFilter implementation mockUserResolver.mockImplementation((request, opts) => @@ -350,7 +353,7 @@ describe('findNodeModuleAsync', () => { }); it('passes packageFilter to the resolve module when using the default resolver', async () => { - const packageFilter = jest.fn(); + const packageFilter = jest.fn(); // A resolver that delegates to defaultResolver with a packageFilter implementation mockUserResolverAsync.async.mockImplementation((request, opts) => @@ -652,7 +655,7 @@ describe('Resolver.getModulePaths() -> nodeModulesPaths()', () => { // This test suite won't work otherwise, since we cannot make assumptions // about the test environment when it comes to absolute paths. jest.doMock('graceful-fs', () => ({ - ...jest.requireActual('graceful-fs'), + ...jest.requireActual('graceful-fs'), realPathSync: { native: (dirInput: string) => dirInput, }, diff --git a/packages/jest-runtime/src/__mocks__/createRuntime.js b/packages/jest-runtime/src/__mocks__/createRuntime.js index 2830be96376c..bea84f2b8d38 100644 --- a/packages/jest-runtime/src/__mocks__/createRuntime.js +++ b/packages/jest-runtime/src/__mocks__/createRuntime.js @@ -6,7 +6,7 @@ */ import {tmpdir} from 'os'; -import path from 'path'; +import * as path from 'path'; import {makeGlobalConfig, makeProjectConfig} from '@jest/test-utils'; import {createScriptTransformer} from '@jest/transform'; import NodeEnvironment from 'jest-environment-node'; diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js index eebec980006f..ea1859daf358 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js @@ -9,7 +9,7 @@ 'use strict'; import {builtinModules, createRequire} from 'module'; -import path from 'path'; +import * as path from 'path'; import {pathToFileURL} from 'url'; import slash from 'slash'; import {onNodeVersions} from '@jest/test-utils'; diff --git a/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts b/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts index 309fb223bff2..35976982beff 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts +++ b/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts @@ -6,8 +6,8 @@ * */ -import os from 'os'; -import path from 'path'; +import * as os from 'os'; +import * as path from 'path'; import {promises as fs} from 'graceful-fs'; import type {Config} from '@jest/types'; import type Runtime from '..'; diff --git a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts index b3cee8cc1f5b..fb7ac24fd812 100644 --- a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts +++ b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts @@ -13,8 +13,8 @@ import type {Frame} from 'jest-message-util'; import {saveInlineSnapshots} from '../InlineSnapshots'; jest.mock('prettier', () => { - const realPrettier: typeof import('prettier') = - jest.requireActual('prettier'); + const realPrettier = + jest.requireActual('prettier'); const mockPrettier: typeof import('prettier') = { format: (text, opts) => realPrettier.format(text, { @@ -23,7 +23,7 @@ jest.mock('prettier', () => { ], ...opts, }), - getFileInfo: {sync: () => ({inferredParser: 'babel'})}, + getFileInfo: {sync: () => ({ignored: false, inferredParser: 'babel'})}, resolveConfig: {sync: jest.fn()}, version: realPrettier.version, }; diff --git a/packages/jest-source-map/src/__tests__/getCallsite.test.ts b/packages/jest-source-map/src/__tests__/getCallsite.test.ts index fed6ab25e748..2ad5847464b0 100644 --- a/packages/jest-source-map/src/__tests__/getCallsite.test.ts +++ b/packages/jest-source-map/src/__tests__/getCallsite.test.ts @@ -11,7 +11,9 @@ import getCallsite from '../getCallsite'; jest.mock('graceful-fs'); jest.mock('@jridgewell/trace-mapping', () => { - const actual = jest.requireActual('@jridgewell/trace-mapping'); + const actual = jest.requireActual( + '@jridgewell/trace-mapping', + ); return { ...actual, diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index 5785e98c05a4..82e1711d8f7e 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -58,7 +58,7 @@ jest ...jest.requireActual('jest-util'), createDirectory: jest.fn(), })) - .mock('path', () => jest.requireActual('path').posix); + .mock('path', () => jest.requireActual('path').posix); jest.mock( 'test_preprocessor', diff --git a/scripts/build.mjs b/scripts/build.mjs index c99674fa91bb..9733369104ce 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -16,8 +16,8 @@ * node ./scripts/build.mjs /users/123/jest/packages/jest-111/src/111.js */ -import assert from 'assert'; -import path from 'path'; +import * as assert from 'assert'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import babel from '@babel/core'; import chalk from 'chalk'; diff --git a/scripts/buildTs.mjs b/scripts/buildTs.mjs index f7c077de66fa..0a1ca1a64240 100644 --- a/scripts/buildTs.mjs +++ b/scripts/buildTs.mjs @@ -5,9 +5,9 @@ * LICENSE file in the root directory of this source tree. */ -import assert from 'assert'; -import os from 'os'; -import path from 'path'; +import * as assert from 'assert'; +import * as os from 'os'; +import * as path from 'path'; import chalk from 'chalk'; import execa from 'execa'; import globby from 'globby'; diff --git a/scripts/buildUtils.mjs b/scripts/buildUtils.mjs index 9e12bededb69..f03b9c42ac15 100644 --- a/scripts/buildUtils.mjs +++ b/scripts/buildUtils.mjs @@ -5,9 +5,9 @@ * LICENSE file in the root directory of this source tree. */ -import assert from 'assert'; +import * as assert from 'assert'; import {createRequire} from 'module'; -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import chalk from 'chalk'; import fs from 'graceful-fs'; diff --git a/scripts/bundleTs.mjs b/scripts/bundleTs.mjs index 75b7f1e3f683..f81606a83e07 100644 --- a/scripts/bundleTs.mjs +++ b/scripts/bundleTs.mjs @@ -6,7 +6,7 @@ */ import {createRequire} from 'module'; -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import { CompilerState, diff --git a/scripts/remove-examples.mjs b/scripts/remove-examples.mjs index b94e0f573a1a..26c18bab4a6a 100644 --- a/scripts/remove-examples.mjs +++ b/scripts/remove-examples.mjs @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import fs from 'graceful-fs'; import config from '../jest.config.mjs'; diff --git a/scripts/verifyOldTs.mjs b/scripts/verifyOldTs.mjs index fae39e66a4cb..d749a8ea9572 100644 --- a/scripts/verifyOldTs.mjs +++ b/scripts/verifyOldTs.mjs @@ -6,7 +6,7 @@ */ import {createRequire} from 'module'; -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import chalk from 'chalk'; import execa from 'execa'; diff --git a/scripts/verifyPnP.mjs b/scripts/verifyPnP.mjs index 56d3916c6c90..0232e410fe2b 100644 --- a/scripts/verifyPnP.mjs +++ b/scripts/verifyPnP.mjs @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import chalk from 'chalk'; import dedent from 'dedent'; diff --git a/scripts/watch.mjs b/scripts/watch.mjs index bfb6a3e2c722..629a96d8b09d 100644 --- a/scripts/watch.mjs +++ b/scripts/watch.mjs @@ -10,7 +10,7 @@ */ import {execSync} from 'child_process'; -import path from 'path'; +import * as path from 'path'; import {fileURLToPath} from 'url'; import chalk from 'chalk'; import chokidar from 'chokidar'; diff --git a/website/versioned_docs/version-28.x/Configuration.md b/website/versioned_docs/version-28.x/Configuration.md index 36f1e1fa4a80..482848450aba 100644 --- a/website/versioned_docs/version-28.x/Configuration.md +++ b/website/versioned_docs/version-28.x/Configuration.md @@ -1329,7 +1329,7 @@ Example: ```js // my-custom-environment -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; class CustomEnvironment extends NodeEnvironment { constructor(config, context) { diff --git a/website/versioned_docs/version-28.x/Puppeteer.md b/website/versioned_docs/version-28.x/Puppeteer.md index b954c5be25cb..5752f7cba96d 100644 --- a/website/versioned_docs/version-28.x/Puppeteer.md +++ b/website/versioned_docs/version-28.x/Puppeteer.md @@ -84,7 +84,7 @@ const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); const puppeteer = require('puppeteer'); -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); diff --git a/website/versioned_docs/version-29.0/Configuration.md b/website/versioned_docs/version-29.0/Configuration.md index e5c949a185a5..d82728b9d899 100644 --- a/website/versioned_docs/version-29.0/Configuration.md +++ b/website/versioned_docs/version-29.0/Configuration.md @@ -1799,7 +1799,7 @@ Example: ```js // my-custom-environment -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; class CustomEnvironment extends NodeEnvironment { constructor(config, context) { diff --git a/website/versioned_docs/version-29.0/Puppeteer.md b/website/versioned_docs/version-29.0/Puppeteer.md index b954c5be25cb..5752f7cba96d 100644 --- a/website/versioned_docs/version-29.0/Puppeteer.md +++ b/website/versioned_docs/version-29.0/Puppeteer.md @@ -84,7 +84,7 @@ const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); const puppeteer = require('puppeteer'); -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); diff --git a/website/versioned_docs/version-29.1/Configuration.md b/website/versioned_docs/version-29.1/Configuration.md index 428f592bf02c..9f780fdc5949 100644 --- a/website/versioned_docs/version-29.1/Configuration.md +++ b/website/versioned_docs/version-29.1/Configuration.md @@ -1807,7 +1807,7 @@ Example: ```js // my-custom-environment -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; class CustomEnvironment extends NodeEnvironment { constructor(config, context) { diff --git a/website/versioned_docs/version-29.1/Puppeteer.md b/website/versioned_docs/version-29.1/Puppeteer.md index b954c5be25cb..5752f7cba96d 100644 --- a/website/versioned_docs/version-29.1/Puppeteer.md +++ b/website/versioned_docs/version-29.1/Puppeteer.md @@ -84,7 +84,7 @@ const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); const puppeteer = require('puppeteer'); -const NodeEnvironment = require('jest-environment-node').default; +const NodeEnvironment = require('jest-environment-node').TestEnvironment; const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');