timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
737 stars 39 forks source link

No longer working with the latest version of Jest and TypeScript #94

Open PaulRBerg opened 2 years ago

PaulRBerg commented 2 years ago

Description

Given the following code:

import { jest } from "@jest/globals";
import type { SpyInstance } from "jest-mock";
import type { ExecSyncOptions } from "node:child_process";

import { isInGitRepository } from "../../src/helpers/git";

describe("tests", function () {
  let execSyncMock: SpyInstance<string | Buffer, [command: string, options?: ExecSyncOptions | undefined]>;

  beforeEach(function () {
    when(execSyncMock)
      .calledWith("git rev-parse --is-inside-work-tree", { stdio: "ignore" })
      .mockImplementationOnce(function () {
        throw new Error();
      });
  });

  test("it returns false", function () {
    expect(isInGitRepository()).toBe(false);
  });
});

The TypeScript compilation fails with the following error:

Argument of type 'SpyInstance<string | Buffer, [command: string, options?: ExecSyncOptions | undefined]>' is not assignable to parameter of type '((command: string, options?: ExecSyncOptions | undefined) => unknown) | MockInstance<unknown, [command: string, options?: ExecSyncOptions | undefined]>'.
  Type 'SpyInstance<string | Buffer, [command: string, options?: ExecSyncOptions | undefined]>' is not assignable to type 'MockInstance<unknown, [command: string, options?: ExecSyncOptions | undefined]>'.
    The types of 'mock.results' are incompatible between these types.
      Type 'MockFunctionResult[]' is not assignable to type 'MockResult<unknown>[]'.
        Type 'MockFunctionResult' is not assignable to type 'MockResult<unknown>'.
          Type 'MockFunctionResult' is not assignable to type 'MockResultReturn<unknown>'.
            Types of property 'type' are incompatible.
              Type 'MockFunctionResultType' is not assignable to type '"return"'.
                Type '"throw"' is not assignable to type '"return"'.ts(2345)

Environment

PaulRBerg commented 2 years ago

Side note: I have also moved to a pure ESM package so that's another potential cause for this error. As per the Jest documentation, mocking is currently not well supported in ESM:

Please note that we currently don't support jest.mock in a clean way in ESM, but that is something we intend to add proper support for in the future.

xenoterracide commented 2 years ago

ugh, pure esm... currently the bane of my existence, was looking forward to using this, but currently seems like it won't be usable.