Skip to content

Commit

Permalink
[dsch] fix for toBe method
Browse files Browse the repository at this point in the history
  • Loading branch information
DScheglov committed Apr 15, 2024
1 parent 53b59b7 commit cba180e
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/engine/to-be.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@ import { Predicate } from '../rules';
import { throwTypeError } from './throw-type-error';
import { CasterFn, Guard } from './types';

const spy = <Args extends any[], R>(fn: (...args: Args) => R) => {
let isCalled: boolean = false;
const result = (...args: Args) => {
isCalled = true;
return fn(...args);
};

Object.defineProperty(result, 'isCalled', {
get: () => isCalled,
});

return result as {
(...args: Args): R;
isCalled: boolean;
};
};

export const toBe =
<T, S extends T>(
casterFn: CasterFn<T>,
Expand All @@ -11,7 +28,11 @@ export const toBe =
) =>
withName(
(value, context, reportError = throwTypeError) => {
const typedValue = casterFn(value, context, reportError);
const spyReportError = spy(reportError);
const typedValue = casterFn(value, context, spyReportError);

if (spyReportError.isCalled) return typedValue;

if (!predicate(typedValue)) {
reportError(`${typeName} expected${context ? ` in ${context}` : ''} but "${value}" received.`, context);
return undefined as any as never;
Expand Down

0 comments on commit cba180e

Please sign in to comment.