Mock functions
Rstest provides some utility functions to help you mock functions powered by tinyspy.
rstest.fn
export interface Mock<T extends Function> extends MockInstance<T> {
(...args: Parameters<T>): ReturnType<T>;
}
export type MockFn = <T extends Function>(fn?: T) => Mock<T>;
Creates a spy on a function.
const sayHi = rstest.fn((name: string) => `hi ${name}`);
const res = sayHi('bob');
expect(res).toBe('hi bob');
expect(sayHi).toHaveBeenCalledTimes(1);
rstest.spyOn
export type SpyFn = (
obj: Record<string, any>,
methodName: string,
accessType?: 'get' | 'set',
) => MockInstance;
Creates a spy on a method of an object.
const sayHi = () => 'hi';
const hi = {
sayHi,
};
const spy = rstest.spyOn(hi, 'sayHi');
expect(hi.sayHi()).toBe('hi');
expect(spy).toHaveBeenCalled();
rstest.isMockFunction
- Type:
(fn: any) => fn is MockInstance
Determines if the given function is a mocked function.
rstest.clearAllMocks
Clears the mock.calls
, mock.instances
, mock.contexts
and mock.results
properties of all mocks.
rstest.resetAllMocks
Clears all mocks properties and reset each mock's implementation to its original.
rstest.restoreAllMocks
Reset all mocks and restore original descriptors of spied-on objects.
More