my-swiss-knife: - v1.9.9
    Preparing search index...

    Function withMock

    • Wraps a function and attaches a mock version. The returned function calls the original, and .mocked() calls the mock.

      Type Parameters

      • TArgs extends unknown[]

        Argument types of the function.

      • TReturn

        Return type of the function.

      Parameters

      Returns (...args: TArgs) => TReturn & { mocked: (...args: TArgs) => TReturn }

      Function with attached .mocked() method.

      const realFn = (x: number) => x * 2;
      const mockFn = (x: number) => 42;
      const wrapped = withMock(realFn, mockFn);

      wrapped(3); // 6
      wrapped.mocked(3); // 42
      export function withMock<TArgs extends unknown[], TReturn>(
      fn: (...args: TArgs) => TReturn,
      mockFn: (...args: TArgs) => TReturn
      ): ((...args: TArgs) => TReturn) & { mocked: (...args: TArgs) => TReturn } {
      return Object.assign(fn, { mocked: mockFn });
      }