跳到主要内容

GenericAssertions

GenericAssertions 类提供了可用于对测试中任何值进行断言的断言方法。通过调用 expect() 可以创建一个新的 GenericAssertions 实例:

import { test, expect } from '@playwright/test';

test('assert a value', async ({ page }) => {
const value = 1;
expect(value).toBe(2);
});

方法

any

Added in: v1.9 genericAssertions.any

expect.any() 匹配从 constructor 创建的任何对象实例或对应的原始类型。在 expect(value).toEqual() 中使用它来执行模式匹配。

用法

// 匹配类的实例
class Example {}
expect(new Example()).toEqual(expect.any(Example));

// 匹配任意数字
expect({ prop: 1 }).toEqual({ prop: expect.any(Number) });

// 匹配任意字符串
expect('abc').toEqual(expect.any(String));

参数

  • constructor Function#

    预期对象的构造函数,如 ExampleClass,或原始包装类型如 Number


anything

Added in: v1.9 genericAssertions.anything

expect.anything() 会匹配除 nullundefined 外的所有值。可在 expect(value).toEqual() 中使用它来进行模式匹配。

用法

const value = { prop: 1 };
expect(value).toEqual({ prop: expect.anything() });
expect(value).not.toEqual({ otherProp: expect.anything() });

arrayContaining

Added in: v1.9 genericAssertions.arrayContaining

expect.arrayContaining() 会匹配包含预期数组中所有元素的数组(顺序不限)。注意接收到的数组可以是预期数组的超集,包含一些额外元素。

expect(value).toEqual() 中使用此方法进行模式匹配。

用法

expect([1, 2, 3]).toEqual(expect.arrayContaining([3, 1]));
expect([1, 2, 3]).not.toEqual(expect.arrayContaining([1, 4]));

参数

  • expected Array<Object>#

    预期数组,它是接收值的子集。

closeTo

新增于: v1.9 genericAssertions.closeTo

比较浮点数的近似相等性。在 expect(value).toEqual() 方法中使用此方法进行模式匹配。当仅比较两个数字时,建议使用 expect(value).toBeCloseTo()

用法

expect({ prop: 0.1 + 0.2 }).not.toEqual({ prop: 0.3 });
expect({ prop: 0.1 + 0.2 }).toEqual({ prop: expect.closeTo(0.3, 5) });

参数

  • expected number#

    期望值。

  • numDigits number (可选)#

    必须相等的小数点后的位数。


objectContaining

新增于: v1.9 genericAssertions.objectContaining

expect.objectContaining() 用于匹配包含并符合预期对象中所有属性的对象。注意接收到的对象可能是预期对象的超集,可以包含一些额外属性。

expect(value).toEqual() 方法中使用此方法进行模式匹配。对象属性可以使用匹配器来进一步放宽预期条件。参见示例。

用法

// 断言部分属性
expect({ foo: 1, bar: 2 }).toEqual(expect.objectContaining({ foo: 1 }));

// 属性上也可以使用匹配器
expect({ foo: 1, bar: 2 }).toEqual(expect.objectContaining({ bar: expect.any(Number) }));

// 子属性的复杂匹配
expect({
list: [1, 2, 3],
obj: { prop: 'Hello world!', another: 'some other value' },
extra: 'extra',
}).toEqual(expect.objectContaining({
list: expect.arrayContaining([2, 3]),
obj: expect.objectContaining({ prop: expect.stringContaining('Hello') }),
}));

参数

  • expected Object#

    包含部分属性的预期对象模式。


stringContaining

Added in: v1.9 genericAssertions.stringContaining

expect.stringContaining() 用于匹配包含预期子字符串的字符串。在 expect(value).toEqual() 方法中使用此方法进行模式匹配。

用法

expect('Hello world!').toEqual(expect.stringContaining('Hello'));

参数

  • expected string#

    预期包含的子字符串。


stringMatching

Added in: v1.9 genericAssertions.stringMatching

expect.stringMatching() 用于匹配符合预期模式的字符串。在 expect(value).toEqual() 方法中使用此方法进行模式匹配。

用法

expect('123ms').toEqual(expect.stringMatching(/\d+m?s/));

// 在另一个匹配器中使用
expect({
status: 'passed',
time: '123ms',
}).toEqual({
status: expect.stringMatching(/passed|failed/),
time: expect.stringMatching(/\d+m?s/),
});

参数


toBe

Added in: v1.9 genericAssertions.toBe

通过调用 Object.is 将值与期望值进行比较。此方法通过引用比较对象而非其内容,类似于严格相等运算符 ===

用法

const value = { prop: 1 };
expect(value).toBe(value);
expect(value).not.toBe({});
expect(value.prop).toBe(1);

参数


toBeCloseTo

Added in: v1.9 genericAssertions.toBeCloseTo

比较浮点数是否近似相等。在比较浮点数时,应使用此方法而非 expect(value).toBe()

用法

expect(0.1 + 0.2).not.toBe(0.3);
expect(0.1 + 0.2).toBeCloseTo(0.3, 5);

参数

  • expected number#

    期望值。

  • numDigits number (可选)#

    必须相等的小数点后位数。


toBeDefined

Added in: v1.9 genericAssertions.toBeDefined

确保值不为 undefined

用法

const value = null;
expect(value).toBeDefined();

toBeFalsy

Added in: v1.9 genericAssertions.toBeFalsy

确保值在布尔上下文中为假,即 false0''nullundefinedNaN 之一。当不关心具体值时使用此方法。

用法

const value = null;
expect(value).toBeFalsy();

toBeGreaterThan

Added in: v1.9 genericAssertions.toBeGreaterThan

确保数字或大整数满足 value > expected

用法

const value = 42;
expect(value).toBeGreaterThan(1);

参数

  • expected number | [bigint]#

    要比较的值。


toBeGreaterThanOrEqual

Added in: v1.9 genericAssertions.toBeGreaterThanOrEqual

确保数值或大整数满足 value >= expected 条件。

用法

const value = 42;
expect(value).toBeGreaterThanOrEqual(42);

参数

  • expected number | [bigint]#

    用于比较的目标值。


toBeInstanceOf

Added in: v1.9 genericAssertions.toBeInstanceOf

确保值是某个类的实例。使用 instanceof 运算符进行判断。

用法

expect(page).toBeInstanceOf(Page);

class Example {}
expect(new Example()).toBeInstanceOf(Example);

参数

  • expected Function#

    目标类或构造函数。


toBeLessThan

Added in: v1.9 genericAssertions.toBeLessThan

确保数值或大整数满足 value < expected 条件。

用法

const value = 42;
expect(value).toBeLessThan(100);

参数

  • expected number | [bigint]#

    用于比较的目标值。


toBeLessThanOrEqual

添加于: v1.9 genericAssertions.toBeLessThanOrEqual

确保数值或大整数满足 value <= expected 条件。

用法

const value = 42;
expect(value).toBeLessThanOrEqual(42);

参数

  • expected number | [bigint]#

    用于比较的期望值。


toBeNaN

添加于: v1.9 genericAssertions.toBeNaN

确保值为 NaN

用法

const value = NaN;
expect(value).toBeNaN();

toBeNull

添加于: v1.9 genericAssertions.toBeNull

确保值为 null

用法

const value = null;
expect(value).toBeNull();

toBeTruthy

添加于: v1.9 genericAssertions.toBeTruthy

确保值在布尔上下文中为真(即false0''nullundefinedNaN)。当不关心具体值时使用此方法。

用法

const value = { example: 'value' };
expect(value).toBeTruthy();

toBeUndefined

添加于: v1.9 genericAssertions.toBeUndefined

确保值为 undefined

用法

const value = undefined;
expect(value).toBeUndefined();

toContain(expected)

Added in: v1.9 genericAssertions.toContain(expected)

确保字符串值包含预期的子字符串。比较区分大小写。

用法

const value = 'Hello, World';
expect(value).toContain('World');
expect(value).toContain(',');

参数

  • expected string#

    预期的子字符串。


toContain(expected)

Added in: v1.9 genericAssertions.toContain(expected)

确保值是 ArraySet 类型且包含预期项。

用法

const value = [1, 2, 3];
expect(value).toContain(2);
expect(new Set(value)).toContain(2);

参数

  • expected Object#

    集合中预期的值。


toContainEqual

v1.9 版本新增 genericAssertions.toContainEqual

确保值是一个 ArraySet 并且包含与预期值相等的项。

对于对象,此方法会递归检查所有字段的相等性,而不是像 expect(value).toContain() 那样通过引用比较对象。

对于原始值,此方法等同于 expect(value).toContain()

用法

const value = [
{ example: 1 },
{ another: 2 },
{ more: 3 },
];
expect(value).toContainEqual({ another: 2 });
expect(new Set(value)).toContainEqual({ another: 2 });

参数

  • expected Object#

    集合中期望的值。


toEqual

v1.9 版本新增 genericAssertions.toEqual

将实际值与预期值的内容进行比较,执行"深度相等"检查。

对于对象,此方法会递归检查所有字段的相等性,而不是像expect(value).toBe()那样通过引用比较对象。

对于原始值,此方法等同于expect(value).toBe()

用法

const value = { prop: 1 };
expect(value).toEqual({ prop: 1 });

非严格相等

expect(value).toEqual()执行深度相等检查,比较接收值和预期值的内容。要确保两个对象引用同一实例,请改用expect(value).toBe()

expect(value).toEqual()会忽略undefined属性和数组项,并且不要求对象类型严格相等。如需更严格的匹配,请使用expect(value).toStrictEqual()

模式匹配

expect(value).toEqual()也可用于在以下匹配器的帮助下对对象、数组和原始类型执行模式匹配:

以下示例断言复杂对象中的部分值:

expect({
list: [1, 2, 3],
obj: { prop: 'Hello world!', another: 'some other value' },
extra: 'extra',
}).toEqual(expect.objectContaining({
list: expect.arrayContaining([2, 3]),
obj: expect.objectContaining({ prop: expect.stringContaining('Hello') }),
}));

参数


toHaveLength

添加于: v1.9 genericAssertions.toHaveLength

确保值具有等于预期值.length属性。适用于数组和字符串。

用法

expect('Hello, World').toHaveLength(12);
expect([1, 2, 3]).toHaveLength(3);

参数


toHaveProperty

添加于: v1.9 genericAssertions.toHaveProperty

确保对象在提供的 keyPath 路径上存在属性,并可选择检查该属性是否等于预期值。相等性检查是递归进行的,类似于 expect(value).toEqual()

用法

const value = {
a: {
b: [42],
},
c: true,
};
expect(value).toHaveProperty('a.b');
expect(value).toHaveProperty('a.b', [42]);
expect(value).toHaveProperty('a.b[0]', 42);
expect(value).toHaveProperty('c');
expect(value).toHaveProperty('c', true);

参数

  • keyPath string#

    属性路径。使用点表示法 a.b 检查嵌套属性,使用索引表示法 a[2] 检查嵌套数组项。

  • expected Object (可选)#

    用于比较属性的可选预期值。

toMatch

Added in: v1.9 genericAssertions.toMatch

确保字符串值匹配正则表达式。

用法

const value = 'Is 42 enough?';
expect(value).toMatch(/Is \d+ enough/);

参数


toMatchObject

Added in: v1.9 genericAssertions.toMatchObject

将值的属性内容与预期对象进行"深度相等"比较。与expect(value).toEqual()不同,允许值中包含额外属性,因此可以只检查对象属性的子集。

比较数组时,项目数量必须匹配,且每个项目会递归检查。

用法

const value = {
a: 1,
b: 2,
c: true,
};
expect(value).toMatchObject({ a: 1, c: true });
expect(value).toMatchObject({ b: 2, c: true });

expect([{ a: 1, b: 2 }]).toMatchObject([{ a: 1 }]);

参数

  • expected Object | Array#

    用于匹配的预期对象值。


toStrictEqual

添加于: v1.9 genericAssertions.toStrictEqual

将值的内容expected的内容及类型进行比较。

expect(value).toEqual()的区别:

  • 会检查包含undefined属性的键。例如,{ a: undefined, b: 2 } 不匹配 { b: 2 }
  • 会检查数组稀疏性。例如,[, 1] 不匹配 [undefined, 1]
  • 会检查对象类型是否相等。例如,具有字段ab的类实例不等于具有字段ab的字面量对象

用法

const value = { prop: 1 };
expect(value).toStrictEqual({ prop: 1 });

参数


toThrow

Added in: v1.9 genericAssertions.toThrow

调用函数并确保其抛出错误。

可选地与expected进行比较。允许的预期值:

  • 正则表达式 - 错误消息应匹配该模式
  • 字符串 - 错误消息应包含该子字符串
  • 错误对象 - 错误消息应等于该对象的message属性
  • 错误类 - 错误对象应是该类的实例

用法

expect(() => {
throw new Error('Something bad');
}).toThrow();

expect(() => {
throw new Error('Something bad');
}).toThrow(/something/);

expect(() => {
throw new Error('Something bad');
}).toThrow(Error);

参数

  • expected Object (可选)#

    预期的错误消息或错误对象。


toThrowError

Added in: v1.9 genericAssertions.toThrowError

expect(value).toThrow()的别名。

用法

expect(() => {
throw new Error('Something bad');
}).toThrowError();

参数

  • expected Object (可选)#

    预期的错误消息或错误对象。


属性

not

添加于: v1.9 genericAssertions.not

使断言检查相反的条件。例如,以下代码会通过:

const value = 1;
expect(value).not.toBe(2);

用法

expect(value).not

类型