ronantakizawa/codereview-bench huggingface dataset:
Repository: facebook/jest
File: e2e/__tests__/listTests.test.ts (TypeScript)

Code before:
      fs.unlinkSync(outputFilePath);
    });
    it('causes tests to be saved in the file as JSON', () => {
      const {exitCode, stdout} = runJest('list-tests', [
        '--listTests',
        '--json',
        '--outputFile',
        outputFilePath,
      ]);

      expect(exitCode).toBe(0);
      expect(stdout).toBe('');

      const outputFileExists = fs.existsSync(outputFilePath);
      expect(outputFileExists).toBe(true);

      const outputFileContent = fs.readFileSync(outputFilePath, 'utf8');
      expect(() => JSON.parse(outputFileContent)).not.toThrow();
      expect(
        JSON.stringify(
          JSON.parse(outputFileContent).map(normalizePaths).sort(),
        ),
      ).toMatchSnapshot();
    });
    it('causes tests to be saved in the file in different lines', () => {
      const {exitCode, stdout} = runJest('list-tests', [
        '--listTests',
        '--outputFile',
        outputFilePath,
      ]);

      expect(exitCode).toBe(0);
      expect(stdout).toBe('');

      const outputFileExists = fs.existsSync(outputFilePath);
      expect(outputFileExists).toBe(true);

      const outputFileContent = fs.readFileSync(outputFilePath, 'utf8');
      expect(
        normalizePaths(outputFileContent).split('\n').sort().join('\n'),
      ).toMatchSnapshot();
    });
  });
});


Review comment (suggestion):
```suggestion

    it('causes tests to be saved in the file in different lines', () => {
```

Code after:
      fs.unlinkSync(outputFilePath);
    });
    it('causes tests to be saved in the file as JSON', () => {
      const {exitCode, stdout} = runJest('list-tests', [
        '--listTests',
        '--json',
        '--outputFile',
        outputFilePath,
      ]);

      expect(exitCode).toBe(0);
      expect(stdout).toBe('');

      const outputFileExists = fs.existsSync(outputFilePath);
      expect(outputFileExists).toBe(true);

      const outputFileContent = fs.readFileSync(outputFilePath, 'utf8');
      expect(() => JSON.parse(outputFileContent)).not.toThrow();
      expect(
        JSON.stringify(
          JSON.parse(outputFileContent).map(normalizePaths).sort(),
        ),
      ).toMatchSnapshot();
    });

    it('causes tests to be saved in the file in different lines', () => {
      const {exitCode, stdout} = runJest('list-tests', [
        '--listTests',
        '--outputFile',
        outputFilePath,
      ]);

      expect(exitCode).toBe(0);
      expect(stdout).toBe('');

      const outputFileExists = fs.existsSync(outputFilePath);
      expect(outputFileExists).toBe(true);

      const outputFileContent = fs.readFileSync(outputFilePath, 'utf8');
      expect(
        normalizePaths(outputFileContent).split('\n').sort().join('\n'),
      ).toMatchSnapshot();
    });
  });
});
Repository: facebook/jest
File: packages/expect/src/asymmetricMatchers.ts (TypeScript)

Code before:
  MatcherState,
} from './types';

const functionToString = Function.prototype.toString;

function fnNameFor(func: () => unknown) {
  if (func.name) {
    return func.name;
  }

  const matches = functionToString
    .call(func)
    .match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
  return matches ? matches[1] : '<anonymous>';
}

const utils = Object.freeze({
  ...matcherUtils,
  iterableEquality,
  subsetEquality,
});

function getPrototype(obj: object) {
  if (Object.getPrototypeOf) {
    return Object.getPrototypeOf(obj);
  }

  if (obj.constructor.prototype == obj) {
    return null;
  }

  return obj.constructor.prototype;
}

export function hasProperty(
  obj: object | null,
  property: string | symbol,
): boolean {
  if (!obj) {
    return false;
  }

  if (Object.prototype.hasOwnProperty.call(obj, property)) {
    return true;
  }

  return hasProperty(getPrototype(obj), property);
}

export abstract class AsymmetricMatcher<T>
  implements AsymmetricMatcherInterface

Review comment (suggestion):
`Object.getPrototypeOf` has been around for years and years

Code after:
  MatcherState,
} from './types';

const functionToString = Function.prototype.toString;

function fnNameFor(func: () => unknown) {
  if (func.name) {
    return func.name;
  }

  const matches = functionToString
    .call(func)
    .match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
  return matches ? matches[1] : '<anonymous>';
}

const utils = Object.freeze({
  ...matcherUtils,
  iterableEquality,
  subsetEquality,
});

export function hasProperty(
  obj: object | null,
  property: string | symbol,
): boolean {
  if (!obj) {
    return false;
  }

  if (Object.prototype.hasOwnProperty.call(obj, property)) {
    return true;
  }

  return hasProperty(Object.getPrototypeOf(obj), property);
}

export abstract class AsymmetricMatcher<T>
  implements AsymmetricMatcherInterface
{
  $$typeof = Symbol.for('jest.asymmetricMatcher');

  constructor(
    protected sample: T,
    protected inverse = false,
  ) {}

  protected getMatcherContext(): MatcherContext {
    return {
      customTesters: getCustomEqualityTesters(),
      // eslint-disable-next-line @typescript-eslint/no-empty-function
Repository: facebook/jest
File: packages/jest-util/src/setGlobal.ts (TypeScript)

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

import type {Global} from '@jest/types';
import {isShreddable, setNotShreddable} from './shredder';

export default function setGlobal(
  globalToMutate: typeof globalThis | Global.Global,
  key: string | symbol,
  value: unknown,
  shredAfterTeardown = true,
): void {
  Reflect.set(globalToMutate, key, value);
  if (!shredAfterTeardown && isShreddable(value)) {
    setNotShreddable(value);
  }
}


Review comment (suggestion):
Let's not do default true boolean values that require passing "false" to disable. That's a confusing API.

I recommend using a type like `'retain' | 'clear'` or similar, and require it being passed. That way developers can't make mistakes.

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

import type {Global} from '@jest/types';
import {
  canDeleteProperties,
  protectProperties,
} from './garbage-collection-utils';

export default function setGlobal(
  globalToMutate: typeof globalThis | Global.Global,
  key: string | symbol,
  value: unknown,
  afterTeardown: 'clean' | 'retain' = 'clean',
): void {
  Reflect.set(globalToMutate, key, value);
  if (afterTeardown === 'retain' && canDeleteProperties(value)) {
    protectProperties(value);
  }
}
Repository: facebook/jest
File: packages/jest-config/src/readConfigFileAndSetRootDir.ts (TypeScript)

Code before:
        rootDir: path.resolve(path.dirname(configPath), configObject.rootDir),
      };
    }
  } else {
    // If rootDir is not there, we'll set it to this file's __dirname
    configObject = {
      ...configObject,
      rootDir: path.dirname(configPath),
    };
  }

  return configObject;
}

// Load the TypeScript configuration
let extraTSLoaderOptions: RegisterOptions;

const loadTSConfigFile = async (
  configPath: string,
): Promise<Config.InitialOptions> => {
  // Get registered TypeScript compiler instance
  const docblockPragmas = parse(extract(fs.readFileSync(configPath, 'utf8')));
  const tsLoader = docblockPragmas['jest-config-loader'] || 'ts-node';
  const docblockTSLoaderOptions = docblockPragmas['jest-config-loader-options'];

  if (typeof docblockTSLoaderOptions === 'string') {
    extraTSLoaderOptions = JSON.parse(docblockTSLoaderOptions);
  }
  if (Array.isArray(tsLoader)) {
    throw new TypeError(
      `Jest: You can only define a single loader through docblocks, got "${tsLoader.join(
        ', ',
      )}"`,
    );
  }

  const registeredCompiler = await getRegisteredCompiler(
    tsLoader as TsLoaderModule,
  );
  registeredCompiler.enabled(true);

  let configObject = interopRequireDefault(require(configPath)).default;

  // In case the config is a function which imports more Typescript code
  if (typeof configObject === 'function') {
    configObject = await configObject();
  }

  registeredCompiler.enabled(false);

  return configObject;

Review comment (suggestion):
these should be passed to `esbuild-register` as well

Code after:
      };
    }
  } else {
    // If rootDir is not there, we'll set it to this file's __dirname
    configObject = {
      ...configObject,
      rootDir: path.dirname(configPath),
    };
  }

  return configObject;
}

// Load the TypeScript configuration
let extraTSLoaderOptions: Record<string, unknown>;

const loadTSConfigFile = async (
  configPath: string,
): Promise<Config.InitialOptions> => {
  // Get registered TypeScript compiler instance
  const docblockPragmas = parse(extract(fs.readFileSync(configPath, 'utf8')));
  const tsLoader = docblockPragmas['jest-config-loader'] || 'ts-node';
  const docblockTSLoaderOptions = docblockPragmas['jest-config-loader-options'];

  if (typeof docblockTSLoaderOptions === 'string') {
    extraTSLoaderOptions = JSON.parse(docblockTSLoaderOptions);
  }
  if (Array.isArray(tsLoader)) {
    throw new TypeError(
      `Jest: You can only define a single loader through docblocks, got "${tsLoader.join(
        ', ',
      )}"`,
    );
  }

  const registeredCompiler = await getRegisteredCompiler(
    tsLoader as TsLoaderModule,
  );
  registeredCompiler.enabled(true);

  let configObject = interopRequireDefault(require(configPath)).default;

  // In case the config is a function which imports more Typescript code
  if (typeof configObject === 'function') {
    configObject = await configObject();
  }

  registeredCompiler.enabled(false);

  return configObject;
};
Repository: facebook/jest
File: packages/expect/src/toThrowMatchers.ts (TypeScript)

Code before:

  return error.message;
}

function buildSerializeError(error: {[key: string]: any}) {
  if (!isObject(error)) {
    return error;
  }

  const result: {[key: string]: any} = {};
  for (const name of Object.getOwnPropertyNames(error).sort()) {
    if (['stack', 'fileName', 'lineNumber'].includes(name)) {
      continue;
    }
    if (name === 'cause') {
      result[name] = buildSerializeError(error['cause']);
      continue;
    }
    result[name] = error[name];
  }

  return result;
}

function isObject(obj: unknown) {
  return !!obj && typeof obj === 'object';
}

function messageAndCause(error: Error) {
  return error.cause === undefined ? 'message' : 'message and cause';
}

export default matchers;


Review comment (suggestion):
```suggestion
  return obj != null && typeof obj === 'object';
```

Code after:
}

function buildSerializeError(error: {[key: string]: any}) {
  if (!isObject(error)) {
    return error;
  }

  const result: {[key: string]: any} = {};
  for (const name of Object.getOwnPropertyNames(error).sort()) {
    if (['stack', 'fileName', 'lineNumber'].includes(name)) {
      continue;
    }
    if (name === 'cause') {
      result[name] = buildSerializeError(error['cause']);
      continue;
    }
    result[name] = error[name];
  }

  return result;
}

function isObject(obj: unknown) {
  return obj != null && typeof obj === 'object';
}

function messageAndCause(error: Error) {
  return error.cause === undefined ? 'message' : 'message and cause';
}

export default matchers;
Repository: facebook/jest
File: packages/expect/src/toThrowMatchers.ts (TypeScript)

Code before:
          message,
          typeof expected.exec === 'function' ? expected.exec(message) : null,
        )
      }\n`;
    }

    return `${label + printReceived(message)}\n`;
  }

  if (key === 'name') {
    return thrown.isError
      ? `${label + printReceived(thrown.value.name)}\n`
      : '';
  }

  if (key === 'value') {
    return thrown.isError ? '' : `${label + printReceived(thrown.value)}\n`;
  }

  return '';
};

const formatStack = (thrown: Thrown | null) => {
  if (thrown === null || !thrown.isError) {
    return '';
  } else {
    const config = {
      rootDir: process.cwd(),
      testMatch: [],
    };
    const options = {
      noStackTrace: false,
    };
    if (thrown.value instanceof AggregateError) {
      return formatExecError(thrown.value, config, options);
    } else {
      return formatStackTrace(
        separateMessageFromStack(thrown.value.stack!).stack,
        config,
        options,
      );
    }
  }
};

function createMessageAndCauseMessage(error: Error): string {
  if (error.cause instanceof Error) {
    return `{ message: ${error.message}, cause: ${createMessageAndCauseMessage(
      error.cause,
    )}}`;
  }

Review comment (suggestion):
we cannot use this as `expect` is meant to work in the browser (and `rootDir` might not even be `cwd`).

If we are to do this, we'll need to pass the config object somehow

Code after:
        )
      }\n`;
    }

    return `${label + printReceived(message)}\n`;
  }

  if (key === 'name') {
    return thrown.isError
      ? `${label + printReceived(thrown.value.name)}\n`
      : '';
  }

  if (key === 'value') {
    return thrown.isError ? '' : `${label + printReceived(thrown.value)}\n`;
  }

  return '';
};

const formatStack = (thrown: Thrown | null) => {
  if (thrown === null || !thrown.isError) {
    return '';
  } else {
    const config = {
      rootDir: process.cwd(),
      testMatch: [],
    };
    const options = {
      noStackTrace: false,
    };
    if (thrown.value instanceof AggregateError) {
      return formatExecError(thrown.value, config, options);
    } else {
      return formatStackTrace(
        separateMessageFromStack(thrown.value.stack!).stack,
        config,
        options,
      );
    }
  }
};

function createMessageAndCause(error: Error) {
  if (error.cause) {
    const seen = new WeakSet();
    return JSON.stringify(buildSerializeError(error), (_, value) => {
      if (isObject(value)) {
        if (seen.has(value)) return;
        seen.add(value); // stop circular references
      }
Repository: facebook/jest
File: e2e/__tests__/typescriptConfigFile.test.ts (TypeScript)

Code before:
    export default {
      testRegex: [ commonRegex, '__tests__/mytest.beta.js' ]
    };`,
    'common.ts': "export default '__tests__/mytest.common.js$';",
  });

  const {stdout, stderr, exitCode} = runJest(
    DIR,
    ['--projects', 'alpha.config.ts', 'beta.config.ts'],
    {
      skipPkgJsonCheck: true,
    },
  );

  expect(stderr).toContain('PASS __tests__/mytest.alpha.js');
  expect(stderr).toContain('PASS __tests__/mytest.beta.js');
  expect(stderr).toContain('PASS __tests__/mytest.common.js');
  expect(stderr.replace('PASS __tests__/mytest.common.js', '')).toContain(
    'PASS __tests__/mytest.common.js',
  );
  expect(stderr).toContain('Test Suites: 4 passed, 4 total');
  expect(exitCode).toBe(0);
  expect(stdout).toBe('');
});

onNodeVersions('<=23.6', () => {
  test("works with single typescript config that does not import anything with project's moduleResolution set to Node16", () => {
    const {configs} = getConfig(
      'typescript-config/modern-module-resolution',
      [],
      {
        skipPkgJsonCheck: true,
      },
    );

    expect(configs).toHaveLength(1);
    expect(configs[0].displayName).toEqual({
      color: 'white',
      name: 'Config from modern ts file',
    });
  });
});


Review comment (bug):
Node resolution modes cannot be configured via `tsconfig.json` in modern node TS - it just uses modern node resolution by default.

This test fails anyways, because it requires transpilation to happen - the `package.json` contains `type: "commonjs"` and the `jest.config.ts` is written in ESM style. 
That fails native node. It would work with `type: "module"`, but we wouldn't really test what this test is about at this point - so I'm skipping it.

Code after:
    export default {
      testRegex: [ commonRegex, '__tests__/mytest.beta.js' ]
    };`,
    'common.ts': "export default '__tests__/mytest.common.js$';",
  });

  const {stdout, stderr, exitCode} = runJest(
    DIR,
    ['--projects', 'alpha.config.ts', 'beta.config.ts'],
    {
      skipPkgJsonCheck: true,
    },
  );

  expect(stderr).toContain('PASS __tests__/mytest.alpha.js');
  expect(stderr).toContain('PASS __tests__/mytest.beta.js');
  expect(stderr).toContain('PASS __tests__/mytest.common.js');
  expect(stderr.replace('PASS __tests__/mytest.common.js', '')).toContain(
    'PASS __tests__/mytest.common.js',
  );
  expect(stderr).toContain('Test Suites: 4 passed, 4 total');
  expect(exitCode).toBe(0);
  expect(stdout).toBe('');
});

onNodeVersions('<23.6', () => {
  test("works with single typescript config that does not import anything with project's moduleResolution set to Node16", () => {
    const {configs} = getConfig(
      'typescript-config/modern-module-resolution',
      [],
      {
        skipPkgJsonCheck: true,
      },
    );

    expect(configs).toHaveLength(1);
    expect(configs[0].displayName).toEqual({
      color: 'white',
      name: 'Config from modern ts file',
    });
  });
});
Repository: facebook/jest
File: e2e/__tests__/toMatchInlineSnapshotCrlf.test.ts (TypeScript)

Code before:

const readFile = (filename: string) =>
  fs.readFileSync(path.join(TESTS_DIR, filename), 'utf8');

beforeAll(() => {
  runYarnInstall(DIR);
});
beforeEach(() => {
  cleanup(TESTS_DIR);
  cleanup(JEST_CONFIG_PATH);
  cleanup(PRETTIER_RC_PATH);
});
afterAll(() => {
  cleanup(TESTS_DIR);
  cleanup(JEST_CONFIG_PATH);
  cleanup(PRETTIER_RC_PATH);
});

test('prettier with crlf newlines', () => {
  writeFiles(DIR, {
    'jest.config.js': `
        module.exports = {prettierPath: require.resolve('prettier')};
      `,
  });
  writeFiles(DIR, {
    '.prettierrc': '{"endOfLine": "crlf"}',
  });
  writeFiles(TESTS_DIR, {
    'test.ts': `\r
        test('snapshots', () => {\r
          expect({test: 1}).toMatchInlineSnapshot();\r
\r
          expect({test: 2}).toMatchInlineSnapshot();\r
        });\r
      `,
  });
  const {stderr, exitCode} = runJest(DIR, ['--ci=false']);
  expect(stderr).toContain('Snapshots:   2 written, 2 total');
  expect(exitCode).toBe(0);

  const fileAfter = readFile('test.ts');
  expect(fileAfter).toBe(`test("snapshots", () => {\r
  expect({ test: 1 }).toMatchInlineSnapshot(\`\r
    {\r
      "test": 1,\r
    }\r
  \`);\r
\r
  expect({ test: 2 }).toMatchInlineSnapshot(\`\r
    {\r
      "test": 2,\r

Review comment (bug):
Note that this file cannot exist in the `to-match-inline-snapshot-crlf` test directory, as it would cause Jest's own usage of Prettier to format everything in the directory to have CRLF line endings, which then get normalized to LF by git and cause Prettier checks to fail, as CRLF is expected. An alternative could be to set up a dedicated .gitattributes file in the folder to instruct Git to use CRLF for this directory wholesale, but I'd rather not check in any CRLF into Git at all.

Code after:

const readFile = (filename: string) =>
  fs.readFileSync(path.join(TESTS_DIR, filename), 'utf8');

beforeAll(() => {
  runYarnInstall(DIR);
});
beforeEach(() => {
  cleanup(TESTS_DIR);
  cleanup(JEST_CONFIG_PATH);
  cleanup(PRETTIER_RC_PATH);
});
afterAll(() => {
  cleanup(TESTS_DIR);
  cleanup(JEST_CONFIG_PATH);
  cleanup(PRETTIER_RC_PATH);
});

test('prettier with crlf newlines', () => {
  writeFiles(DIR, {
    'jest.config.js': `
        module.exports = {prettierPath: require.resolve('prettier')};
      `,
  });
  writeFiles(DIR, {
    '.prettierrc': '{"endOfLine": "crlf"}',
  });
  writeFiles(TESTS_DIR, {
    'test.ts': `test('snapshots', () => {
    expect({test: 1}).toMatchInlineSnapshot();

    expect({test: 2}).toMatchInlineSnapshot();
  });
`.replaceAll('\n', '\r\n'),
  });
  const {stderr, exitCode} = runJest(DIR, ['--ci=false']);
  expect(stderr).toContain('Snapshots:   2 written, 2 total');
  expect(exitCode).toBe(0);

  const fileAfter = readFile('test.ts');
  expect(fileAfter).toBe(
    `test("snapshots", () => {
  expect({ test: 1 }).toMatchInlineSnapshot(\`
    {
      "test": 1,
    }
  \`);

  expect({ test: 2 }).toMatchInlineSnapshot(\`
    {
      "test": 2,
Repository: facebook/jest
File: e2e/native-esm-typescript/__tests__/double.test.ts (TypeScript)

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

import {double} from '../double';

test('test double', () => {
  expect(double(2)).toBe(4);
});

test('test import.meta', () => {
  expect(typeof import.meta.url).toBe('string');
});

// Source: https://github.com/jestjs/jest/issues/15823
test('test double with dynamic import', () => {
  expect(double(2)).toBe(4);
});


Review comment (suggestion):
Should this test use the newly added function `doubleWithDynamicImport`? The test title indicates that dynamic import is used but the test body doesn't say that

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

import {double, doubleWithDynamicImport} from '../double';

test('test double', () => {
  expect(double(2)).toBe(4);
});

test('test import.meta', () => {
  expect(typeof import.meta.url).toBe('string');
});

// Source: https://github.com/jestjs/jest/issues/15823
test('test double with dynamic import', () => {
  expect(doubleWithDynamicImport(2)).toBe(4);
});