chore: fix some type errors in tests (#13360)

This commit is contained in:
Simen Bekkhus
2022-10-03 09:15:59 +02:00
committed by GitHub
parent ed24b75de2
commit dd35bc05b1
84 changed files with 1195 additions and 1160 deletions
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -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');
+2 -2
View File
@@ -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 '../';
+3 -3
View File
@@ -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';
+2 -2
View File
@@ -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 '../';
+3 -3
View File
@@ -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';
+1 -1
View File
@@ -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));
+1 -1
View File
@@ -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() {
@@ -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`;
@@ -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));
@@ -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) {
@@ -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) {
@@ -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) {
@@ -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;
}
}
+6 -6
View File
@@ -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() {
+2 -2
View File
@@ -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');
+2 -2
View File
@@ -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');
@@ -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;
@@ -36,7 +36,7 @@ describe('.hasAssertions()', () => {
});
it('throws if expected is not undefined', () => {
jestExpect(() => {
expect(() => {
// @ts-expect-error
jestExpect.hasAssertions(2);
}).toThrowErrorMatchingSnapshot();
@@ -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;
@@ -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;
@@ -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');
});
File diff suppressed because it is too large Load Diff
@@ -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');
+1 -1
View File
@@ -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 {
//...
@@ -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.',
@@ -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.');
});
@@ -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<Circus.HookType>)('%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.',
);
},
);
});
@@ -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']);
@@ -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 '../';
@@ -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<typeof import('path')>('path').posix)
.mock('graceful-fs', () => {
const realFs = jest.requireActual('fs');
const realFs = jest.requireActual<typeof import('fs')>('fs');
return {
...realFs,
@@ -35,7 +35,9 @@ let expectedPathAbs: string;
let expectedPathAbsAnother: string;
let virtualModuleRegexes: Array<RegExp>;
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<typeof import('path')>('path').win32,
);
require('jest-resolve').default.findNodeModule = findNodeModule;
});
@@ -7,7 +7,7 @@
import {readConfigs} from '../index';
jest.mock('graceful-fs', () => ({
...jest.requireActual('fs'),
...jest.requireActual<typeof import('fs')>('fs'),
existsSync: jest.fn(() => true),
lstatSync: jest.fn(() => ({
isDirectory: () => false,
+1 -1
View File
@@ -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);
@@ -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<typeof import('fs')>('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 () => {
@@ -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';
@@ -10,7 +10,7 @@ import type {Config} from '@jest/types';
import getNoTestsFoundMessage from '../getNoTestsFoundMessage';
jest.mock('jest-util', () => ({
...jest.requireActual('jest-util'),
...jest.requireActual<typeof import('jest-util')>('jest-util'),
isInteractive: true,
}));
@@ -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;
@@ -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,
@@ -12,7 +12,7 @@ import each from '../';
const noop = () => {};
const expectFunction = expect.any(Function);
const get = (object, lensPath) =>
const get = <T>(object: T, lensPath: Array<string>): T =>
lensPath.reduce((acc, key) => acc[key], object);
const getGlobalTestMocks = () => {
@@ -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 = <T>(
object: T,
lensPath: Array<string>,
): ((...args: Array<unknown>) => 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<Global.TestFrameworkGlobals> => {
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});
});
@@ -287,7 +287,7 @@ describe('FakeTimers', () => {
});
it('cancels a callback even from native nextTick', () => {
const nativeNextTick = jest.fn();
const nativeNextTick = jest.fn<typeof process.nextTick>();
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<typeof setImmediate>();
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<typeof process.nextTick>();
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<typeof setImmediate>();
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<typeof setImmediate>();
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<typeof console.warn>()};
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<typeof setImmediate>();
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<typeof setImmediate>();
const nativeClearImmediate = jest.fn<typeof clearImmediate>();
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<typeof setImmediate>();
const nativeClearImmediate = jest.fn<typeof clearImmediate>();
const global = {
clearImmediate: nativeClearImmediate,
@@ -119,7 +119,7 @@ describe('FakeTimers', () => {
const timers = new FakeTimers({config: makeProjectConfig(), global});
timers.useFakeTimers();
const runOrder = [];
const runOrder: Array<string> = [];
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<string> = [];
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<string> = [];
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<string> = [];
global.setTimeout(function cb() {
runOrder.push('mock1');
@@ -7,7 +7,7 @@
*/
'use strict';
import path from 'path';
import * as path from 'path';
import getMockName from '../getMockName';
describe('getMockName', () => {
@@ -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');
@@ -6,7 +6,7 @@
*
*/
import crypto from 'crypto';
import * as crypto from 'crypto';
import * as path from 'path';
function mockHashContents(contents) {
@@ -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';
@@ -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', () => {
@@ -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';
@@ -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();
});
@@ -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<HookType>)('%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.',
);
},
);
});
@@ -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.',
@@ -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<QueueableFn['fn']>(_next => {});
const fnTwo = jest.fn<QueueableFn['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);
@@ -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'));
@@ -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.');
});
@@ -5,8 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
'use strict';
import LeakDetector from '../index';
const gc = globalThis.gc;
@@ -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!');
});
});
@@ -206,12 +206,12 @@ describe('printDiffOrStringify', () => {
});
test('map', () => {
const expected: Map<unknown, unknown> = new Map([
const expected = new Map<string, unknown>([
['a', 1],
['b', expect.any(Number)],
['c', 3],
]);
const received: Map<unknown, unknown> = new Map([
const received = new Map<string, unknown>([
['a', 1],
['b', 2],
['c', 2],
@@ -254,13 +254,13 @@ describe('printDiffOrStringify', () => {
});
test('circular map', () => {
const expected: Map<unknown, unknown> = new Map([
const expected = new Map<string, unknown>([
['a', 1],
['b', expect.any(Number)],
['c', 3],
]);
expected.set('circular', expected);
const received: Map<unknown, unknown> = new Map([
const received = new Map<string, unknown>([
['a', 1],
['b', 2],
['c', 2],
@@ -19,7 +19,7 @@ import {
const rootDir = tempy.directory();
jest.mock('graceful-fs', () => ({
...jest.requireActual('fs'),
...jest.requireActual<typeof import('fs')>('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.<anonymous> (${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.<anonymous> (${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.<anonymous> (${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);
});
@@ -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;
@@ -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');
@@ -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(() => {
@@ -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();
});
});
@@ -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';
@@ -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<typeof import('resolve')>('resolve');
const m = jest.fn((...args) => originalModule(...args));
const m = jest.fn<typeof import('resolve')>((...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<PackageFilter>();
// 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<PackageFilter>();
// 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<typeof import('graceful-fs')>('graceful-fs'),
realPathSync: {
native: (dirInput: string) => dirInput,
},
@@ -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';
@@ -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';
@@ -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 '..';
@@ -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<typeof import('prettier')>('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,
};
@@ -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<typeof import('@jridgewell/trace-mapping')>(
'@jridgewell/trace-mapping',
);
return {
...actual,
@@ -58,7 +58,7 @@ jest
...jest.requireActual<typeof import('jest-util')>('jest-util'),
createDirectory: jest.fn(),
}))
.mock('path', () => jest.requireActual('path').posix);
.mock('path', () => jest.requireActual<typeof import('path')>('path').posix);
jest.mock(
'test_preprocessor',
+2 -2
View File
@@ -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';
+3 -3
View File
@@ -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';
+2 -2
View File
@@ -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';
+1 -1
View File
@@ -6,7 +6,7 @@
*/
import {createRequire} from 'module';
import path from 'path';
import * as path from 'path';
import {fileURLToPath} from 'url';
import {
CompilerState,
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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';
@@ -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) {
@@ -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');
@@ -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) {
@@ -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');
@@ -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) {
@@ -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');