Aller au contenu principal

cast()

cast<T>(obj): T

Casts a value to a target type for test access to private members.

💎 Why is this a Hidden Gem?

Encapsulates unsafe casts (as unknown as T or as any, ...) in one place. No more // eslint-disable-next-line @typescript-eslint/no-explicit-any scattered across test files.


Type Parameters

T: T = any

The target type to cast to.


Parameters

obj: unknown

The value to cast.


Returns: T

The value cast to the target type.


Since

2.0.0


Example

class MyClass {
private secret = 42;
}

const instance = new MyClass();
const exposed = cast<{ secret: number }>(instance);
expect(exposed.secret).toBe(42);

Use Cases

Access private members 📌

Bypass TypeScript visibility modifiers to test internal state. Essential for white-box testing of classes.

class Counter {
private count = 0;
}
const instance = new Counter();
const internals = cast<{ count: number }>(instance);
expect(internals.count).toBe(0);

Force incompatible types

Pass intentionally wrong types to test error handling paths.

// Test that function handles invalid input gracefully
const result = myFunction(cast<string>(123));
expect(result.error).toBe('Expected string');