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

Code before:
      mockFn
        .mockImplementationOnce(() => 'Foo')
        .mockImplementationOnce(() => 'Bar');

      expect(mockFn()).toBe('Foo');
      expect(mockFn()).toBe('Bar');
      expect(mockFn()).toBeUndefined();
    });

    it('should fallback to default mock function when no specific mock is available', () => {
      const mockFn = moduleMocker.fn();

      mockFn
        .mockImplementationOnce(() => 'Foo')
        .mockImplementationOnce(() => 'Bar')
        .mockImplementation(() => 'Default');

      expect(mockFn()).toBe('Foo');
      expect(mockFn()).toBe('Bar');
      expect(mockFn()).toBe('Default');
      expect(mockFn()).toBe('Default');
    });
  });

  describe('withImplementation', () => {
    it('sets an implementation which is available within the callback', async () => {
      const mock1 = jest.fn();
      const mock2 = jest.fn();

      const Module = jest.fn(() => ({someFn: mock1}));
      const testFn = function () {
        const m = new Module();
        m.someFn();
      };

      Module.withImplementation(
        () => ({someFn: mock2}),
        () => {
          testFn();
          expect(mock2).toHaveBeenCalled();
          expect(mock1).not.toHaveBeenCalled();
        },
      );

      testFn();
      expect(mock1).toHaveBeenCalled();
    });

    it('returns a promise if the provided callback is asynchronous', async () => {
      const mock1 = jest.fn();
      const mock2 = jest.fn();

Review comment (suggestion):
```suggestion
    it('sets an implementation which is available within the callback', () => {
```

Code after:
      mockFn
        .mockImplementationOnce(() => 'Foo')
        .mockImplementationOnce(() => 'Bar');

      expect(mockFn()).toBe('Foo');
      expect(mockFn()).toBe('Bar');
      expect(mockFn()).toBeUndefined();
    });

    it('should fallback to default mock function when no specific mock is available', () => {
      const mockFn = moduleMocker.fn();

      mockFn
        .mockImplementationOnce(() => 'Foo')
        .mockImplementationOnce(() => 'Bar')
        .mockImplementation(() => 'Default');

      expect(mockFn()).toBe('Foo');
      expect(mockFn()).toBe('Bar');
      expect(mockFn()).toBe('Default');
      expect(mockFn()).toBe('Default');
    });
  });

  describe('withImplementation', () => {
    it('sets an implementation which is available within the callback', () => {
      const mock1 = jest.fn();
      const mock2 = jest.fn();

      const Module = jest.fn(() => ({someFn: mock1}));
      const testFn = function () {
        const m = new Module();
        m.someFn();
      };

      Module.withImplementation(
        () => ({someFn: mock2}),
        () => {
          testFn();
          expect(mock2).toHaveBeenCalled();
          expect(mock1).not.toHaveBeenCalled();
        },
      );

      testFn();
      expect(mock1).toHaveBeenCalled();

      expect.assertions(3);
    });

    it('returns a promise if the provided callback is asynchronous', async () => {
Repository: facebook/jest
File: packages/test-utils/src/ConditionalTest.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.
 */

/* eslint-disable jest/no-focused-tests */

import semver = require('semver');

export function isJestJasmineRun(): boolean {
  return process.env.JEST_JASMINE === '1';
}

export function skipSuiteOnJasmine(): void {
  if (isJestJasmineRun()) {
    test.only('does not work on Jasmine', () => {
      console.warn('[SKIP] Does not work on Jasmine');
    });
  }
}

export function skipSuiteOnJestCircus(): void {
  if (!isJestJasmineRun()) {
    test.only('does not work on jest-circus', () => {
      console.warn('[SKIP] Does not work on jest-circus');
    });
  }
}

export function onNodeVersions(
  versionRange: string,
  testBody: () => void,

Review comment (suggestion):
Just a reminder. It is not possible to import from `@jest/globals`, because `@jest/globals` depend on `expect` which depends on `@jest/test-utils`. That’s circular. In contrary `@jest/types` currently depends only on `@jest/schemas`.

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 semver = require('semver');
import type {Global} from '@jest/types';

declare const describe: Global.TestFrameworkGlobals['describe'];
declare const test: Global.TestFrameworkGlobals['test'];

export function isJestJasmineRun(): boolean {
  return process.env.JEST_JASMINE === '1';
}

export function skipSuiteOnJasmine(): void {
  if (isJestJasmineRun()) {
    test.only('does not work on Jasmine', () => {
      console.warn('[SKIP] Does not work on Jasmine');
    });
  }
}

export function skipSuiteOnJestCircus(): void {
  if (!isJestJasmineRun()) {
    test.only('does not work on jest-circus', () => {
      console.warn('[SKIP] Does not work on jest-circus');
    });
  }
}

export function onNodeVersions(
Repository: facebook/jest
File: packages/jest-util/src/isPromise.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.
 */

const isPromise = (candidate: unknown): candidate is PromiseLike<unknown> =>
  candidate != null &&
  (typeof candidate === 'object' || typeof candidate === 'function') &&
  typeof (candidate as any).then === 'function';
export default isPromise;


Review comment (suggestion):
Perhaps? Just to avoid `any`? Or the point is to be explicit that this is still `any`?

```suggestion
  typeof (candidate as PromiseLike<unknown>).then === 'function';
```

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.
 */

export default function isPromise<T = unknown>(
  candidate: unknown,
): candidate is PromiseLike<T> {
  return (
    candidate != null &&
    (typeof candidate === 'object' || typeof candidate === 'function') &&
    typeof (candidate as any).then === 'function'
  );
}
Repository: facebook/jest
File: examples/angular/app.component.spec.ts (TypeScript)

Code before:
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {describe, expect, it, jest} from '@jest/globals';

import {AppComponent} from './app.component';
import {DataService} from './shared/data.service';

const title = 'Test';
const getTitleFn = jest.fn<DataService['getTitle']>().mockReturnValue(title);
const dataServiceSpy = jest.fn().mockImplementation(
  (): Partial<DataService> => ({
    getTitle: getTitleFn,
  }),
);

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [{provide: DataService, useClass: dataServiceSpy}],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
  }));

  it('should create the app', () => {
    expect(app).toBeTruthy();
  });

  it("should have as title 'angular'", () => {
    expect(app.title).toEqual(title);
  });

  it('should render title in a h1 tag', () => {
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain(
      `Welcome to ${title}!`,
    );
  });
});


Review comment (suggestion):
`async` is deprecated and replaced by `waitForAsync`. See https://angular.io/api/core/testing#functions

Code after:
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {describe, expect, it, jest} from '@jest/globals';

import {AppComponent} from './app.component';
import {DataService} from './shared/data.service';

const title = 'Test';
const getTitleFn = jest.fn(() => title);
const dataServiceSpy = jest.fn(
  (): Partial<DataService> => ({
    getTitle: getTitleFn,
  }),
);

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [{provide: DataService, useClass: dataServiceSpy}],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
  }));

  it('should create the app', () => {
    expect(app).toBeTruthy();
  });

  it("should have as title 'angular'", () => {
    expect(app.title).toEqual(title);
  });

  it('should render title in a h1 tag', () => {
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain(
      `Welcome to ${title}!`,
    );
  });
});
Repository: facebook/jest
File: examples/angular/app.component.spec.ts (TypeScript)

Code before:
import {ComponentFixture, TestBed, async} from '@angular/core/testing';

import {AppComponent} from './app.component';
import {DataService} from './shared/data.service';

const title = 'Test';
const getTitleFn = jest.fn().mockReturnValue(title);
const dataServiceSpy = jest.fn().mockImplementation(
  (): Partial<DataService> => ({
    getTitle: getTitleFn,
  }),
);

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [{provide: DataService, useClass: dataServiceSpy}],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
  }));

  it('should create the app', () => {
    expect(app).toBeTruthy();
  });

  it("should have as title 'angular'", () => {
    expect(app.title).toEqual(title);
  });


Review comment (suggestion):
This way types are inferred for `getTitleFn` and `dataServiceSpy`.

Code after:
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {describe, expect, it, jest} from '@jest/globals';

import {AppComponent} from './app.component';
import {DataService} from './shared/data.service';

const title = 'Test';
const getTitleFn = jest.fn(() => title);
const dataServiceSpy = jest.fn(
  (): Partial<DataService> => ({
    getTitle: getTitleFn,
  }),
);

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [{provide: DataService, useClass: dataServiceSpy}],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
  }));

  it('should create the app', () => {
    expect(app).toBeTruthy();
  });

  it("should have as title 'angular'", () => {
    expect(app.title).toEqual(title);
  });
Repository: facebook/jest
File: packages/babel-jest/src/__tests__/index.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 {TransformOptions as BabelTransformOptions} from '@babel/core';
import type {EncodedSourceMap} from '@jridgewell/trace-mapping';
import {makeProjectConfig} from '@jest/test-utils';
import type {TransformOptions} from '@jest/transform';
import babelJest, {createTransformer} from '../index';
import {loadPartialConfig} from '../loadBabelConfig';
jest.mock('../loadBabelConfig', () => {
  const actual =
    jest.requireActual<typeof import('@babel/core')>('@babel/core');

  return {
    loadPartialConfig: jest.fn((...args) => actual.loadPartialConfig(...args)),
    loadPartialConfigAsync: jest.fn((...args) =>
      actual.loadPartialConfigAsync(...args),
    ),
  };
});

const defaultBabelJestTransformer = babelJest.createTransformer();

//Mock data for all the tests
const sourceString = `
const sum = (a, b) => a+b;
const difference = (a, b) => a-b;

const customMultiply = (obj, mul) => {
    const {a, ...rest} = obj;

Review comment (suggestion):
Or would it be better to reexport from `jest/transform`? Not sure..

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 {
  BabelFileResult,
  TransformOptions as BabelTransformOptions,
} from '@babel/core';
import {makeProjectConfig} from '@jest/test-utils';
import type {TransformOptions} from '@jest/transform';
import babelJest, {createTransformer} from '../index';
import {loadPartialConfig} from '../loadBabelConfig';
jest.mock('../loadBabelConfig', () => {
  const actual =
    jest.requireActual<typeof import('@babel/core')>('@babel/core');

  return {
    loadPartialConfig: jest.fn((...args) => actual.loadPartialConfig(...args)),
    loadPartialConfigAsync: jest.fn((...args) =>
      actual.loadPartialConfigAsync(...args),
    ),
  };
});

const defaultBabelJestTransformer = babelJest.createTransformer();

//Mock data for all the tests
const sourceString = `
const sum = (a, b) => a+b;
const difference = (a, b) => a-b;
Repository: facebook/jest
File: packages/expect/src/asymmetricMatchers.ts (TypeScript)

Code before:
        break;
      }
    }

    return this.inverse ? !result : result;
  }

  toString() {
    return `Object${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'object';
  }
}

class StringContaining extends AsymmetricMatcher<string> {
  constructor(sample: string, inverse = false) {
    if (!isA('String', sample)) {
      throw new Error('Expected is not a string');
    }
    super(sample, inverse);
  }

  asymmetricMatch(other: string) {
    const result = isA('String', other) && other.includes(this.sample);

    return this.inverse ? !result : result;
  }

  toString() {
    return `String${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'string';
  }
}

class StringMatching extends AsymmetricMatcher<RegExp> {
  constructor(sample: string | RegExp, inverse = false) {
    if (!isA('String', sample) && !isA('RegExp', sample)) {
      throw new Error('Expected is not a String or a RegExp');
    }
    super(new RegExp(sample), inverse);
  }

  asymmetricMatch(other: string) {
    const result = isA('String', other) && this.sample.test(other);

    return this.inverse ? !result : result;

Review comment (suggestion):
This is just an internal type, user facing external types do not change. The point is that internally `other` is of type `unknown` in all the matchers. As an illustration see this test (all matchers have similar tests and that is a problem for typechecking):

https://github.com/facebook/jest/blob/8759d63787b832af1fc9ac0ec2cc57b6f325ba9a/packages/expect/src/__tests__/asymmetricMatchers.test.ts#L321

At first it sounded strange, but reasons are very well explained in https://github.com/facebook/jest/pull/7107

Code after:
        break;
      }
    }

    return this.inverse ? !result : result;
  }

  toString() {
    return `Object${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'object';
  }
}

class StringContaining extends AsymmetricMatcher<string> {
  constructor(sample: string, inverse = false) {
    if (!isA('String', sample)) {
      throw new Error('Expected is not a string');
    }
    super(sample, inverse);
  }

  asymmetricMatch(other: unknown) {
    const result = isA<string>('String', other) && other.includes(this.sample);

    return this.inverse ? !result : result;
  }

  toString() {
    return `String${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'string';
  }
}

class StringMatching extends AsymmetricMatcher<RegExp> {
  constructor(sample: string | RegExp, inverse = false) {
    if (!isA('String', sample) && !isA('RegExp', sample)) {
      throw new Error('Expected is not a String or a RegExp');
    }
    super(new RegExp(sample), inverse);
  }

  asymmetricMatch(other: unknown) {
    const result = isA<string>('String', other) && this.sample.test(other);

    return this.inverse ? !result : result;
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-runner';
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):
This is for `Config.InitialOptions`, right? If so, better import it directly from `@jest/types`:

```suggestion
import type {Config} from '@jest/types';
```

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):
If I remember it right, this should work:

```suggestion
describe(readInitialOptions, () => {
```

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
});