Mock functions

Rstest 基于 tinyspy 提供了一些工具方法帮助你进行函数的模拟(mock)。

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>;

创建一个 mock 函数。

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;

对一个对象的方法进行 mock。

const sayHi = () => 'hi';
const hi = {
  sayHi,
};

const spy = rstest.spyOn(hi, 'sayHi');

expect(hi.sayHi()).toBe('hi');

expect(spy).toHaveBeenCalled();

rstest.isMockFunction

  • 类型: (fn: any) => fn is MockInstance

判断给定的函数是否为 mock 函数。

rstest.clearAllMocks

  • 类型: () => Rstest

清除所有 mock 的 mock.callsmock.instancesmock.contextsmock.results 属性。

rstest.resetAllMocks

  • 类型: () => Rstest

清除所有 mock 属性,并将每个 mock 的实现重置为其原始实现。

rstest.restoreAllMocks

  • 类型: () => Rstest

重置所有 mock,并恢复被 mock 的对象的原始描述符。