wellcrafted
Version:
Delightful TypeScript patterns for elegant, type-safe applications
59 lines (57 loc) • 1.97 kB
JavaScript
import { isErr, isOk } from "./result-C_ph_izC.js";
import { extractErrorMessage } from "./error-BkeqDeUq.js";
import "./tap-err-BENAkFsH.js";
import "./result-pV2mfn0W.js";
//#region src/testing.ts
/**
* Test-only assertion helpers for `Result` values.
*
* These helpers intentionally **throw**. A failed expectation should abort the
* test, and every test runner reports a thrown error as a failure. Tests are
* the one place throwing is the correct control flow, so these are fenced into
* the `wellcrafted/testing` entry point and kept out of `wellcrafted/result`,
* which stays throw-free. Importing from `wellcrafted/testing` in production
* code is a smell worth linting against.
*
* They are framework-agnostic: they throw a plain `Error` rather than calling
* into a specific runner, so they work under bun, vitest, jest, or
* `node:test`.
*/
/**
* Asserts that `result` is `Ok` and returns its `data`.
*
* Throws if `result` is `Err`. The returned value is narrowed to the success
* type, so no optional chaining or casting is needed at the call site.
*
* @example
* ```ts
* import { expectOk } from "wellcrafted/testing";
*
* const value = expectOk(parseConfig(raw)); // typed as the success value
* ```
*/
function expectOk(result) {
if (!isOk(result)) throw new Error(`Expected Ok, but got Err: ${extractErrorMessage(result.error)}`);
return result.data;
}
/**
* Asserts that `result` is `Err` and returns its `error`.
*
* Throws if `result` is `Ok`. The returned value is narrowed to the error
* type, so no optional chaining or casting is needed at the call site.
*
* @example
* ```ts
* import { expectErr } from "wellcrafted/testing";
*
* const error = expectErr(parseConfig("not valid"));
* expect(error.name).toBe("ConfigParseError");
* ```
*/
function expectErr(result) {
if (!isErr(result)) throw new Error("Expected Err, but got Ok");
return result.error;
}
//#endregion
export { expectErr, expectOk };
//# sourceMappingURL=testing.js.map