ronantakizawa/codereview-bench huggingface dataset:
Repository: facebook/jest
File: packages/jest-config/src/__tests__/readInitialOptions.test.ts (TypeScript)

Code before:
/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import type {Config} from '@jest/types';
import {readInitialOptions} from '../index';

describe(readInitialOptions.name, () => {
  test('should be able to use serialized jest config', async () => {
    const inputConfig = {jestConfig: 'serialized'};
    const {config, configPath} = await readInitialOptions(
      JSON.stringify(inputConfig),
    );
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toEqual(null);
  });

  test('should allow deserialized options', async () => {
    const inputConfig = {jestConfig: 'deserialized'};
    const {config, configPath} = await readInitialOptions(undefined, {
      packageRootOrConfig: inputConfig as Config.InitialOptions,
      parentConfigDirname: process.cwd(),
    });
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toEqual(null);
  });
  // Note: actual file reading is tested in e2e test
});


Review comment (suggestion):
```suggestion
    expect(configPath).toBeNull();
```

Code after:
/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import type {Config} from '@jest/types';
import {readInitialOptions} from '../index';

describe(readInitialOptions, () => {
  test('should be able to use serialized jest config', async () => {
    const inputConfig = {jestConfig: 'serialized'};
    const {config, configPath} = await readInitialOptions(
      JSON.stringify(inputConfig),
    );
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toBeNull();
  });

  test('should allow deserialized options', async () => {
    const inputConfig = {jestConfig: 'deserialized'};
    const {config, configPath} = await readInitialOptions(undefined, {
      packageRootOrConfig: inputConfig as Config.InitialOptions,
      parentConfigDirname: process.cwd(),
    });
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toBeNull();
  });
  // Note: actual file reading is tested in e2e test
});
Repository: facebook/jest
File: packages/jest-config/src/__tests__/readInitialOptions.test.ts (TypeScript)

Code before:
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import type {Config} from '@jest/types';
import {readInitialOptions} from '../index';

describe(readInitialOptions.name, () => {
  test('should be able to use serialized jest config', async () => {
    const inputConfig = {jestConfig: 'serialized'};
    const {config, configPath} = await readInitialOptions(
      JSON.stringify(inputConfig),
    );
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toEqual(null);
  });

  test('should allow deserialized options', async () => {
    const inputConfig = {jestConfig: 'deserialized'};
    const {config, configPath} = await readInitialOptions(undefined, {
      packageRootOrConfig: inputConfig as Config.InitialOptions,
      parentConfigDirname: process.cwd(),
    });
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toEqual(null);
  });
  // Note: actual file reading is tested in e2e test
});


Review comment (suggestion):
```suggestion
    expect(configPath).toBeNull();
```

Code after:
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import type {Config} from '@jest/types';
import {readInitialOptions} from '../index';

describe(readInitialOptions, () => {
  test('should be able to use serialized jest config', async () => {
    const inputConfig = {jestConfig: 'serialized'};
    const {config, configPath} = await readInitialOptions(
      JSON.stringify(inputConfig),
    );
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toBeNull();
  });

  test('should allow deserialized options', async () => {
    const inputConfig = {jestConfig: 'deserialized'};
    const {config, configPath} = await readInitialOptions(undefined, {
      packageRootOrConfig: inputConfig as Config.InitialOptions,
      parentConfigDirname: process.cwd(),
    });
    expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
    expect(configPath).toBeNull();
  });
  // Note: actual file reading is tested in e2e test
});
Repository: facebook/jest
File: packages/jest-config/src/normalize.ts (TypeScript)

Code before:
  );

  if (
    newOptions.lastCommit ||
    newOptions.changedFilesWithAncestor ||
    newOptions.changedSince
  ) {
    newOptions.onlyChanged = true;
  }

  if (argv.all) {
    newOptions.onlyChanged = false;
    newOptions.onlyFailures = false;
  } else if (newOptions.testPathPattern) {
    // When passing a test path pattern we don't want to only monitor changed
    // files unless `--watch` is also passed.
    newOptions.onlyChanged = newOptions.watch;
  }

  // xoroshiro128plus is used in v8 and is used here (at time of writing)
  newOptions.seed =
    argv.seed ?? Math.floor(0xffffffff * Math.random() - 0x80000000);
  if (newOptions.seed < -0x80000000 || newOptions.seed > 0x7fffffff) {
    throw new ValidationError(
      'Validation Error',
      'seed value is limited from -0x80000000 to 0x7fffffff',
    );
  }

  if (!newOptions.onlyChanged) {
    newOptions.onlyChanged = false;
  }

  if (!newOptions.lastCommit) {
    newOptions.lastCommit = false;
  }

  if (!newOptions.onlyFailures) {
    newOptions.onlyFailures = false;
  }

  if (!newOptions.watchAll) {
    newOptions.watchAll = false;
  }

  // as unknown since it can happen. We really need to fix the types here
  if (
    newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as unknown)
  ) {
    newOptions.moduleNameMapper = [];
  }

Review comment (suggestion):
```suggestion
      'seed value must be between `-0x80000000` and `0x7fffffff` inclusive',
```

Code after:
    10,
  );

  if (
    newOptions.lastCommit ||
    newOptions.changedFilesWithAncestor ||
    newOptions.changedSince
  ) {
    newOptions.onlyChanged = true;
  }

  if (argv.all) {
    newOptions.onlyChanged = false;
    newOptions.onlyFailures = false;
  } else if (newOptions.testPathPattern) {
    // When passing a test path pattern we don't want to only monitor changed
    // files unless `--watch` is also passed.
    newOptions.onlyChanged = newOptions.watch;
  }

  newOptions.showSeed = newOptions.showSeed || argv.showSeed;

  const upperBoundSeedValue = 2 ** 31;

  // xoroshiro128plus is used in v8 and is used here (at time of writing)
  newOptions.seed =
    argv.seed ??
    Math.floor((2 ** 32 - 1) * Math.random() - upperBoundSeedValue);
  if (
    newOptions.seed < -upperBoundSeedValue ||
    newOptions.seed > upperBoundSeedValue - 1
  ) {
    throw new ValidationError(
      'Validation Error',
      `seed value must be between \`-0x80000000\` and \`0x7fffffff\` inclusive - is ${newOptions.seed}`,
    );
  }

  if (!newOptions.onlyChanged) {
    newOptions.onlyChanged = false;
  }

  if (!newOptions.lastCommit) {
    newOptions.lastCommit = false;
  }

  if (!newOptions.onlyFailures) {
    newOptions.onlyFailures = false;
  }

  if (!newOptions.watchAll) {
Repository: facebook/jest
File: e2e/__tests__/jestObject.test.ts (TypeScript)

Code before:
/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as path from 'path';
import runJest from '../runJest';

const dir = path.resolve(__dirname, '../jest-object');

test('passes with seed', () => {
  const result = runJest(dir, ['get-seed.test.js', '--seed', '1234']);
  expect(result.exitCode).toBe(0);
});

test('failes with wrong seed', () => {
  const result = runJest(dir, ['get-seed.test.js', '--seed', '1111']);
  expect(result.exitCode).toBe(1);
});

test('seed always exists', () => {
  const result = runJest(dir, ['any-seed.test.js']);
  expect(result.exitCode).toBe(0);
});


Review comment (bug):
```suggestion
test('fails with wrong seed', () => {
```

Code after:
/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as path from 'path';
import runJest from '../runJest';

const dir = path.resolve(__dirname, '../jest-object');

test('passes with seed', () => {
  const result = runJest(dir, ['get-seed.test.js', '--seed', '1234']);
  expect(result.exitCode).toBe(0);
});

test('fails with wrong seed', () => {
  const result = runJest(dir, ['get-seed.test.js', '--seed', '1111']);
  expect(result.exitCode).toBe(1);
});

test('seed always exists', () => {
  const result = runJest(dir, ['any-seed.test.js']);
  expect(result.exitCode).toBe(0);
});
Repository: facebook/jest
File: packages/jest-core/src/collectHandles.ts (TypeScript)

Code before:
              return ref.deref()?.hasRef() ?? false;
            };
          } else {
            isActive = resource.hasRef.bind(resource);
          }
        } else {
          // Handle that doesn't support hasRef
          isActive = alwaysActive;
        }

        activeHandles.set(asyncId, {error, isActive});
      }
    },
  });

  hook.enable();

  return async () => {
    // Wait briefly for any async resources that have been queued for
    // destruction to actually be destroyed.
    // For example, Node.js TCP Servers are not destroyed until *after* their
    // `close` callback runs. If someone finishes a test from the `close`
    // callback, we will not yet have seen the resource be destroyed here.
    await asyncSleep(100);

    if (activeHandles.size !== 0) {
      // For some special objects such as `TLSWRAP`.
      // Ref: https://github.com/facebook/jest/issues/11665
      runGC();

      await asyncSleep(0);
    }

    hook.disable();

    // Get errors for every async resource still referenced at this moment
    const result = Array.from(activeHandles.values())
      .filter(({isActive}) => isActive())
      .map(({error}) => error);

    activeHandles.clear();
    return result;
  };
}

export function formatHandleErrors(
  errors: Array<Error>,
  config: Config.ProjectConfig,
): Array<string> {
  const stacks = new Set();


Review comment (suggestion):
```suggestion
    if (activeHandles.size > 0) {
```

I find it more readable 🙂

Code after:
          } else {
            isActive = resource.hasRef.bind(resource);
          }
        } else {
          // Handle that doesn't support hasRef
          isActive = alwaysActive;
        }

        activeHandles.set(asyncId, {error, isActive});
      }
    },
  });

  hook.enable();

  return async () => {
    // Wait briefly for any async resources that have been queued for
    // destruction to actually be destroyed.
    // For example, Node.js TCP Servers are not destroyed until *after* their
    // `close` callback runs. If someone finishes a test from the `close`
    // callback, we will not yet have seen the resource be destroyed here.
    await asyncSleep(100);

    if (activeHandles.size > 0) {
      // For some special objects such as `TLSWRAP`.
      // Ref: https://github.com/facebook/jest/issues/11665
      runGC();

      await asyncSleep(0);
    }

    hook.disable();

    // Get errors for every async resource still referenced at this moment
    const result = Array.from(activeHandles.values())
      .filter(({isActive}) => isActive())
      .map(({error}) => error);

    activeHandles.clear();
    return result;
  };
}

export function formatHandleErrors(
  errors: Array<Error>,
  config: Config.ProjectConfig,
): Array<string> {
  const stacks = new Set();

  return (
    errors
Repository: facebook/jest
File: packages/jest-core/src/collectHandles.ts (TypeScript)

Code before:
  }

  // jest-jasmine it or describe call
  if (stack.includes('asyncJestTest') || stack.includes('asyncJestLifecycle')) {
    return true;
  }

  // An async function call from within circus
  if (stack.includes('callAsyncCircusFn')) {
    // jest-circus it or describe call
    return (
      stack.includes('_callCircusTest') || stack.includes('_callCircusHook')
    );
  }

  return false;
}

const alwaysActive = () => true;

// @ts-expect-error: doesn't exist in v12 typings
const hasWeakRef = typeof WeakRef === 'function';

const asyncSleep = promisify(setTimeout);

let gcFunc: Function | undefined = (globalThis as any).gc;
function runGC() {
  if (!gcFunc) {
    v8.setFlagsFromString('--expose-gc');
    gcFunc = vm.runInNewContext('gc');
    v8.setFlagsFromString('--no-expose-gc');
    if (!gcFunc) {
      console.warn(
        'Cannot find `global.gc` function. Please run node with `--expose-gc`',
      );
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      gcFunc = () => {};
    }
  }

  gcFunc();
}

// Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js
// Extracted as we want to format the result ourselves
export default function collectHandles(): HandleCollectionResult {
  const activeHandles = new Map<
    number,
    {error: Error; isActive: () => boolean}
  >();
  const hook = asyncHooks.createHook({

Review comment (suggestion):
```suggestion
let gcFunc: (() => void) | undefined = (globalThis as any).gc;
```

Code after:
  }

  // jest-jasmine it or describe call
  if (stack.includes('asyncJestTest') || stack.includes('asyncJestLifecycle')) {
    return true;
  }

  // An async function call from within circus
  if (stack.includes('callAsyncCircusFn')) {
    // jest-circus it or describe call
    return (
      stack.includes('_callCircusTest') || stack.includes('_callCircusHook')
    );
  }

  return false;
}

const alwaysActive = () => true;

// @ts-expect-error: doesn't exist in v12 typings
const hasWeakRef = typeof WeakRef === 'function';

const asyncSleep = promisify(setTimeout);

let gcFunc: (() => void) | undefined = (globalThis as any).gc;
function runGC() {
  if (!gcFunc) {
    v8.setFlagsFromString('--expose-gc');
    gcFunc = vm.runInNewContext('gc');
    v8.setFlagsFromString('--no-expose-gc');
    if (!gcFunc) {
      throw new Error(
        'Cannot find `global.gc` function. Please run node with `--expose-gc` and report this issue in jest repo.',
      );
    }
  }

  gcFunc();
}

// Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js
// Extracted as we want to format the result ourselves
export default function collectHandles(): HandleCollectionResult {
  const activeHandles = new Map<
    number,
    {error: Error; isActive: () => boolean}
  >();
  const hook = asyncHooks.createHook({
    destroy(asyncId) {
      activeHandles.delete(asyncId);
Repository: facebook/jest
File: packages/jest-worker/src/types.ts (TypeScript)

Code before:
   * the raw output of the worker.
   */
  silent?: boolean;
  /**
   * Used to immediately bind event handlers.
   */
  on?: {
    [WorkerEvents.STATE_CHANGE]:
      | OnStateChangeHandler
      | ReadonlyArray<OnStateChangeHandler>;
  };
};

export type OnStateChangeHandler = (
  state: WorkerStates,
  oldState: WorkerStates,
) => void;

// Messages passed from the parent to the children.

export type ChildMessageInitialize = [
  type: typeof CHILD_MESSAGE_INITIALIZE,
  isProcessed: boolean,
  fileName: string,
  setupArgs: Array<unknown> | undefined,
  workerId: string | undefined,
];

export type ChildMessageCall = [
  type: typeof CHILD_MESSAGE_CALL,
  isProcessed: boolean,
  methodName: string,
  args: Array<unknown>,
];

export type ChildMessageEnd = [
  type: typeof CHILD_MESSAGE_END,
  isProcessed: boolean,
];

export type ChildMessageMemUsage = [type: typeof CHILD_MESSAGE_MEM_USAGE];

export type ChildMessage =
  | ChildMessageInitialize
  | ChildMessageCall
  | ChildMessageEnd
  | ChildMessageMemUsage;

// Messages passed from the children to the parent.

export type ParentMessageCustom = [

Review comment (suggestion):
Does not look like this is `MessagePort`: 

https://github.com/facebook/jest/blob/c791d97114024391b1894d9923688c0a0216cc4f/packages/jest-worker/src/workers/NodeThreadsWorker.ts#L130-L136

Code after:
   * the raw output of the worker.
   */
  silent?: boolean;
  /**
   * Used to immediately bind event handlers.
   */
  on?: {
    [WorkerEvents.STATE_CHANGE]:
      | OnStateChangeHandler
      | ReadonlyArray<OnStateChangeHandler>;
  };
};

export type OnStateChangeHandler = (
  state: WorkerStates,
  oldState: WorkerStates,
) => void;

// Messages passed from the parent to the children.

export type ChildMessageInitialize = [
  type: typeof CHILD_MESSAGE_INITIALIZE,
  isProcessed: boolean,
  fileName: string,
  setupArgs: Array<unknown>,
  workerId: string | undefined,
];

export type ChildMessageCall = [
  type: typeof CHILD_MESSAGE_CALL,
  isProcessed: boolean,
  methodName: string,
  args: Array<unknown>,
];

export type ChildMessageEnd = [
  type: typeof CHILD_MESSAGE_END,
  isProcessed: boolean,
];

export type ChildMessageMemUsage = [type: typeof CHILD_MESSAGE_MEM_USAGE];

export type ChildMessage =
  | ChildMessageInitialize
  | ChildMessageCall
  | ChildMessageEnd
  | ChildMessageMemUsage;

// Messages passed from the children to the parent.

export type ParentMessageCustom = [
Repository: facebook/jest
File: packages/jest-worker/src/types.ts (TypeScript)

Code before:
  /**
   * This is useful for debugging individual tests allowing you to see
   * the raw output of the worker.
   */
  silent?: boolean;
  /**
   * Used to immediately bind event handlers.
   */
  on?: {
    [WorkerEvents.STATE_CHANGE]:
      | OnStateChangeHandler
      | ReadonlyArray<OnStateChangeHandler>;
  };
};

export type OnStateChangeHandler = (
  state: WorkerStates,
  oldState: WorkerStates,
) => void;

// Messages passed from the parent to the children.

export type MessagePort = typeof EventEmitter & {
  postMessage(message: unknown): void;
};

export type MessageChannel = {
  port1: MessagePort;
  port2: MessagePort;
};

export type ChildMessageInitialize = [
  typeof CHILD_MESSAGE_INITIALIZE, // type
  boolean, // processed
  string, // file
  Array<unknown> | undefined, // setupArgs
  MessagePort | undefined, // MessagePort
];

export type ChildMessageCall = [
  typeof CHILD_MESSAGE_CALL, // type
  boolean, // processed
  string, // method
  Array<unknown>, // args
];

export type ChildMessageEnd = [
  typeof CHILD_MESSAGE_END, // type
  boolean, // processed
];


Review comment (suggestion):
Also it looks safe to remove `undefined` (for simplicity): https://github.com/facebook/jest/blob/c791d97114024391b1894d9923688c0a0216cc4f/packages/jest-worker/src/types.ts#L163

Code after:
   * This is useful for debugging individual tests allowing you to see
   * the raw output of the worker.
   */
  silent?: boolean;
  /**
   * Used to immediately bind event handlers.
   */
  on?: {
    [WorkerEvents.STATE_CHANGE]:
      | OnStateChangeHandler
      | ReadonlyArray<OnStateChangeHandler>;
  };
};

export type OnStateChangeHandler = (
  state: WorkerStates,
  oldState: WorkerStates,
) => void;

// Messages passed from the parent to the children.

export type ChildMessageInitialize = [
  type: typeof CHILD_MESSAGE_INITIALIZE,
  isProcessed: boolean,
  fileName: string,
  setupArgs: Array<unknown>,
  workerId: string | undefined,
];

export type ChildMessageCall = [
  type: typeof CHILD_MESSAGE_CALL,
  isProcessed: boolean,
  methodName: string,
  args: Array<unknown>,
];

export type ChildMessageEnd = [
  type: typeof CHILD_MESSAGE_END,
  isProcessed: boolean,
];

export type ChildMessageMemUsage = [type: typeof CHILD_MESSAGE_MEM_USAGE];

export type ChildMessage =
  | ChildMessageInitialize
  | ChildMessageCall
  | ChildMessageEnd
  | ChildMessageMemUsage;

// Messages passed from the children to the parent.
Repository: facebook/jest
File: packages/jest-util/src/__tests__/deepCyclicCopy.test.ts (TypeScript)

Code before:
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import deepCyclicCopy from '../deepCyclicCopy';

it('returns the same value for primitive or function values', () => {
  const fn = () => {};

  expect(deepCyclicCopy(undefined)).toBeUndefined();
  expect(deepCyclicCopy(null)).toBeNull();
  expect(deepCyclicCopy(true)).toBe(true);
  expect(deepCyclicCopy(42)).toBe(42);
  expect(Number.isNaN(deepCyclicCopy(NaN))).toBe(true);
  expect(deepCyclicCopy('foo')).toBe('foo');
  expect(deepCyclicCopy(fn)).toBe(fn);
});

it('does not execute getters/setters, but copies them', () => {
  const fn = jest.fn();
  const obj = {
    // @ts-expect-error
    get foo() {
      fn();
    },
  };
  const copy = deepCyclicCopy(obj);

  expect(Object.getOwnPropertyDescriptor(copy, 'foo')).toBeDefined();
  expect(fn).not.toHaveBeenCalled();
});

it('copies symbols', () => {
  const symbol = Symbol('foo');
  const obj = {[symbol]: 42};

  expect(deepCyclicCopy(obj)[symbol]).toBe(42);
});

it('copies arrays as array objects', () => {
  const array = [null, 42, 'foo', 'bar', [], {}];

  expect(deepCyclicCopy(array)).toEqual(array);
  expect(Array.isArray(deepCyclicCopy(array))).toBe(true);
});

it('handles cyclic dependencies', () => {
  const cyclic: any = {a: 42, subcycle: {}};


Review comment (suggestion):
TypeScript was insisting that a getter should return something.

Code after:
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import deepCyclicCopy from '../deepCyclicCopy';

it('returns the same value for primitive or function values', () => {
  const fn = () => {};

  expect(deepCyclicCopy(undefined)).toBeUndefined();
  expect(deepCyclicCopy(null)).toBeNull();
  expect(deepCyclicCopy(true)).toBe(true);
  expect(deepCyclicCopy(42)).toBe(42);
  expect(Number.isNaN(deepCyclicCopy(NaN))).toBe(true);
  expect(deepCyclicCopy('foo')).toBe('foo');
  expect(deepCyclicCopy(fn)).toBe(fn);
});

it('does not execute getters/setters, but copies them', () => {
  const fn = jest.fn();
  const obj = {
    get foo() {
      fn();
      return;
    },
  };
  const copy = deepCyclicCopy(obj);

  expect(Object.getOwnPropertyDescriptor(copy, 'foo')).toBeDefined();
  expect(fn).not.toHaveBeenCalled();
});

it('copies symbols', () => {
  const symbol = Symbol('foo');
  const obj = {[symbol]: 42};

  expect(deepCyclicCopy(obj)[symbol]).toBe(42);
});

it('copies arrays as array objects', () => {
  const array = [null, 42, 'foo', 'bar', [], {}];

  expect(deepCyclicCopy(array)).toEqual(array);
  expect(Array.isArray(deepCyclicCopy(array))).toBe(true);
});

it('handles cyclic dependencies', () => {
  type Cyclic = {[key: string]: unknown | Cyclic} & {subcycle?: Cyclic};