Files
xo-cash-utils/test/misc.test.ts
2026-07-19 19:15:22 +00:00

71 lines
2.3 KiB
TypeScript

import { expect, test, vi } from 'vitest';
import { tryAsync } from '../source/misc.ts';
/** Spy used to confirm the wrapped async function ran successfully. */
const successFlagFn = vi.fn();
/** Spy used to confirm the error callback was invoked on failure. */
const errorFlagFn = vi.fn();
/**
* Tests that tryAsync invokes the function and skips the error callback on success.
*/
const testTryAsyncCallsFunctionOnSuccess = async (): Promise<void> => {
// Reset spies so prior test runs do not affect call counts.
vi.clearAllMocks();
const successFn = async (): Promise<void> => {
successFlagFn();
};
await tryAsync(successFn);
// The wrapped function should run and no error handler should be called.
expect(successFlagFn).toHaveBeenCalledOnce();
expect(errorFlagFn).not.toHaveBeenCalled();
};
/**
* Tests that tryAsync invokes the error callback when the function throws.
*/
const testTryAsyncCallsErrorCallbackOnFailure = async (): Promise<void> => {
vi.clearAllMocks();
const errorFn = async (): Promise<void> => {
throw new Error('test');
};
await tryAsync(errorFn, errorFlagFn);
// The success path should not run; the error callback should receive the failure.
expect(successFlagFn).not.toHaveBeenCalled();
expect(errorFlagFn).toHaveBeenCalledOnce();
};
/**
* Tests that tryAsync wraps non-Error throws in Error instances before calling the error callback.
*/
const testTryAsyncConvertsNonErrorThrows = async (): Promise<void> => {
vi.clearAllMocks();
const errorFn = async (): Promise<void> => {
/* eslint-disable-next-line */
throw 'test';
};
await tryAsync(errorFn, errorFlagFn);
// Non-Error throws must be normalized to Error before onError is called.
expect(successFlagFn).not.toHaveBeenCalled();
expect(errorFlagFn).toHaveBeenCalledOnce();
expect(errorFlagFn).toHaveBeenCalledWith(new Error('test'));
};
const runTests = async (): Promise<void> => {
test('tryAsync: calls the function and skips the error callback on success', testTryAsyncCallsFunctionOnSuccess);
test('tryAsync: calls the error callback when the function fails', testTryAsyncCallsErrorCallbackOnFailure);
test('tryAsync: converts non-Error throws to Error instances', testTryAsyncConvertsNonErrorThrows);
};
await runTests();