函数 expect

  • 每次您想要测试一个值时,都会使用 expect 函数。您很少会单独调用 expect

    类型参数

    • T = any

    参数

    • actual: T

      应用匹配器的值。

    返回值 JestMatchers<T>

属性

not: InverseAsymmetricMatchers

方法

  • 添加一个模块以格式化特定于应用程序的数据结构以进行序列化。

    参数

    • serializer: Plugin_2

    返回值 void

  • 匹配使用给定构造函数创建的任何内容。您可以在 toEqualtoBeCalledWith 中使用它,而不是字面值。

    参数

    • classType: any

    返回值 any

    function randocall(fn) {
    return fn(Math.floor(Math.random() * 6 + 1));
    }

    test('randocall calls its callback with a number', () => {
    const mock = jest.fn();
    randocall(mock);
    expect(mock).toBeCalledWith(expect.any(Number));
    });
  • 匹配除 null 或 undefined 之外的任何内容。您可以在 toEqualtoBeCalledWith 中使用它,而不是字面值。例如,如果您想检查是否使用非 null 参数调用了模拟函数

    返回值 any

    test('map calls its argument with a non-null argument', () => {
    const mock = jest.fn();
    [1].map(x => mock(x));
    expect(mock).toBeCalledWith(expect.anything());
    });
  • 匹配完全由所提供数组中的元素组成的任何数组。您可以在 toEqualtoBeCalledWith 中使用它,而不是字面值。

    (可选)您可以为元素提供泛型类型。

    类型参数

    • E = any

    参数

    • arr: readonly E[]

    返回值 any

  • 验证在测试期间调用了特定数量的断言。这在测试异步代码时通常很有用,以确保实际调用了回调中的断言。

    参数

    • num: number

    返回值 void

  • 在比较对象属性或数组项中的浮点数时很有用。如果需要比较数字,请改用 .toBeCloseTo

    可选的 numDigits 参数限制要检查的小数点后的位数。对于默认值 2,测试标准是 Math.abs(expected - received) < 0.005(即 10 ** -2 / 2)。

    参数

    • num: number
    • 可选numDigits: number

    返回值 any

  • 您可以使用 expect.extend 将您自己的匹配器添加到 Jest。

    参数

    • obj: ExpectExtendMap

    返回值 void

  • 返回值 MatcherState & Record<string, any>

  • 验证在测试期间至少调用了一个断言。这在测试异步代码时通常很有用,以确保实际调用了回调中的断言。

    返回值 void

  • 匹配递归匹配所提供键的任何对象。这通常与其他非对称匹配器结合使用时很方便。

    (可选)您可以为对象提供泛型类型。这确保了对象包含所需的结构。

    类型参数

    • E = {}

    参数

    • obj: E

    返回值 any

  • 参数

    • state: object

    返回值 void

  • 匹配任何包含完全预期字符串的接收字符串

    参数

    • str: string

    返回值 any

  • 匹配任何包含完全提供的字符串的字符串

    参数

    • str: string | RegExp

    返回值 any