close
logo
Rstest
指南
配置
API
English
简体中文
指南
配置
API
English
简体中文
logo
Rstest
Overview

Test API

Expect
Test
Describe
Hooks

Rstest Utility

Mock modules
Mock functions
MockInstance
Fake timers
Utilities
📝 在 GitHub 上编辑此页
上一页Mock modules
下一页MockInstance

#Mock functions

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

#rstest.fn

  • 别名: rs.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

  • 别名: rs.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

  • 别名: rs.isMockFunction
  • 类型: (fn: any) => fn is MockInstance

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

#rstest.clearAllMocks

  • 别名: rs.clearAllMocks
  • 类型: () => Rstest

清除所有 mock 的 mock.calls、mock.instances、mock.contexts 和 mock.results 属性。

#rstest.resetAllMocks

  • 别名: rs.resetAllMocks
  • 类型: () => Rstest

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

#rstest.restoreAllMocks

  • 别名: rs.restoreAllMocks
  • 类型: () => Rstest

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

#更多

  • Mock 匹配器
  • MockInstance API