Overview
The _unsafeUnwrap() and _unsafeUnwrapErr() methods are designed exclusively for testing. They extract the inner value from a Result without proper error handling, throwing an error if the wrong variant is accessed.
Test Environments OnlyThese methods should never be used in production code. The underscore prefix is a convention indicating they are unsafe. In production, always use safe methods like match(), unwrapOr(), or proper error handling.
Type Signatures
ErrorConfig
_unsafeUnwrap()
Extracts the value from an Ok variant. Throws if called on an Err.
Behavior
- If
Result is Ok: Returns the inner value T
- If
Result is Err: Throws a custom error object
Basic Usage
In Tests
_unsafeUnwrapErr()
Extracts the error from an Err variant. Throws if called on an Ok.
Behavior
- If
Result is Err: Returns the inner error E
- If
Result is Ok: Throws a custom error object
Basic Usage
In Tests
Stack Traces
By default, thrown errors don’t include stack traces. This makes Jest error messages cleaner and easier to read.
Enable Stack Traces
Testing Patterns
Testing Success Cases
Testing Error Cases
Testing with safeTry
Alternative: Compare Results Directly
You don’t always need to unwrap Results in tests. Result instances are comparable:
With Jest/Vitest Matchers
Advanced Testing Patterns
Testing Complex Error Types
Testing Async Results
Snapshot Testing
ESLint Plugin
Use eslint-plugin-neverthrow to enforce proper Result handling:
This ensures you either:
- Call
.match()
- Call
.unwrapOr()
- Call
._unsafeUnwrap() (only in tests)
Why the Underscore Prefix?
The underscore (_) prefix is a naming convention that signals:
- This method is unsafe
- It should only be used in specific contexts (tests)
- It breaks the normal error handling guarantees
- Production code should avoid it
This convention is borrowed from languages like Rust, where unsafe operations are clearly marked.
Key Points
- Only use in tests - Never in production code
_unsafeUnwrap() extracts Ok values, throws on Err
_unsafeUnwrapErr() extracts Err values, throws on Ok
- Stack traces are disabled by default for cleaner test output
- Enable stack traces with
{ withStackTrace: true }
- Consider comparing Results directly instead of unwrapping
- Use ESLint plugin to enforce safe usage
- The underscore prefix indicates unsafe operation