GenericAssertions
GenericAssertions 类提供了断言方法,可用于对测试中的任何值进行断言。通过调用 expect() 创建 GenericAssertions 的新实例:
¥The GenericAssertions class provides assertion methods that can be used to make assertions about any values in the tests. A new instance of GenericAssertions is created by calling expect():
import { test, expect } from '@playwright/test';
test('assert a value', async ({ page }) => {
const value = 1;
expect(value).toBe(2);
});
方法
¥Methods
any
Added in: v1.9expect.any()
匹配从 构造函数 或相应的基本类型创建的任何对象实例。在 expect(value).toEqual() 内部使用它来执行模式匹配。
¥expect.any()
matches any object instance created from the constructor or a corresponding primitive type. Use it inside expect(value).toEqual() to perform pattern matching.
用法
¥Usage
// Match instance of a class.
class Example {}
expect(new Example()).toEqual(expect.any(Example));
// Match any number.
expect({ prop: 1 }).toEqual({ prop: expect.any(Number) });
// Match any string.
expect('abc').toEqual(expect.any(String));
参数
¥Arguments
预期对象(如 ExampleClass
)或原始装箱类型(如 Number
)的构造函数。
¥Constructor of the expected object like ExampleClass
, or a primitive boxed type like Number
.
anything
Added in: v1.9expect.anything()
匹配除 null
和 undefined
之外的所有内容。在 expect(value).toEqual() 内部使用它来执行模式匹配。
¥expect.anything()
matches everything except null
and undefined
. Use it inside expect(value).toEqual() to perform pattern matching.
用法
¥Usage
const value = { prop: 1 };
expect(value).toEqual({ prop: expect.anything() });
expect(value).not.toEqual({ otherProp: expect.anything() });
arrayContaining
Added in: v1.9expect.arrayContaining()
匹配一个包含预期数组中所有元素(按任意顺序)的数组。请注意,接收到的数组可能是预期数组的超集,并包含一些额外的元素。
¥expect.arrayContaining()
matches an array that contains all of the elements in the expected array, in any order. Note that received array may be a superset of the expected array and contain some extra elements.
在 expect(value).toEqual() 内部使用该方法来执行模式匹配。
¥Use this method inside expect(value).toEqual() to perform pattern matching.
用法
¥Usage
expect([1, 2, 3]).toEqual(expect.arrayContaining([3, 1]));
expect([1, 2, 3]).not.toEqual(expect.arrayContaining([1, 4]));
参数
¥Arguments
预期数组是接收值的子集。
¥Expected array that is a subset of the received value.
closeTo
Added in: v1.9比较浮点数是否近似相等。在 expect(value).toEqual() 内部使用该方法来执行模式匹配。当只是比较两个数字时,更喜欢 expect(value).toBeCloseTo()。
¥Compares floating point numbers for approximate equality. Use this method inside expect(value).toEqual() to perform pattern matching. When just comparing two numbers, prefer expect(value).toBeCloseTo().
用法
¥Usage
expect({ prop: 0.1 + 0.2 }).not.toEqual({ prop: 0.3 });
expect({ prop: 0.1 + 0.2 }).toEqual({ prop: expect.closeTo(0.3, 5) });
参数
¥Arguments
期望值。
¥Expected value.
小数点后的小数位数必须相等。
¥The number of decimal digits after the decimal point that must be equal.
objectContaining
Added in: v1.9expect.objectContaining()
匹配包含并匹配预期对象中所有属性的对象。请注意,接收到的对象可能是预期对象的超集,并包含一些额外的属性。
¥expect.objectContaining()
matches an object that contains and matches all of the properties in the expected object. Note that received object may be a superset of the expected object and contain some extra properties.
在 expect(value).toEqual() 内部使用该方法来执行模式匹配。对象属性可以是匹配器以进一步放宽期望。请参阅示例。
¥Use this method inside expect(value).toEqual() to perform pattern matching. Object properties can be matchers to further relax the expectation. See examples.
用法
¥Usage
// Assert some of the properties.
expect({ foo: 1, bar: 2 }).toEqual(expect.objectContaining({ foo: 1 }));
// Matchers can be used on the properties as well.
expect({ foo: 1, bar: 2 }).toEqual(expect.objectContaining({ bar: expect.any(Number) }));
// Complex matching of sub-properties.
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') }),
}));
参数
¥Arguments
包含属性子集的预期对象模式。
¥Expected object pattern that contains a subset of the properties.
stringContaining
Added in: v1.9expect.stringContaining()
匹配包含预期子字符串的字符串。在 expect(value).toEqual() 内部使用该方法来执行模式匹配。
¥expect.stringContaining()
matches a string that contains the expected substring. Use this method inside expect(value).toEqual() to perform pattern matching.
用法
¥Usage
expect('Hello world!').toEqual(expect.stringContaining('Hello'));
参数
¥Arguments
预期的子串。
¥Expected substring.
stringMatching
Added in: v1.9expect.stringMatching()
与接收到的字符串匹配,该字符串又与预期模式匹配。在 expect(value).toEqual() 内部使用该方法来执行模式匹配。
¥expect.stringMatching()
matches a received string that in turn matches the expected pattern. Use this method inside expect(value).toEqual() to perform pattern matching.
用法
¥Usage
expect('123ms').toEqual(expect.stringMatching(/\d+m?s/));
// Inside another matcher.
expect({
status: 'passed',
time: '123ms',
}).toEqual({
status: expect.stringMatching(/passed|failed/),
time: expect.stringMatching(/\d+m?s/),
});
参数
¥Arguments
预期字符串应匹配的模式。
¥Pattern that expected string should match.
toBe
Added in: v1.9通过调用 Object.is
将值与 expected 进行比较。此方法通过引用而不是其内容来比较对象,类似于严格相等运算符 ===
。
¥Compares value with expected by calling Object.is
. This method compares objects by reference instead of their contents, similarly to the strict equality operator ===
.
用法
¥Usage
const value = { prop: 1 };
expect(value).toBe(value);
expect(value).not.toBe({});
expect(value.prop).toBe(1);
参数
¥Arguments
期望值。
¥Expected value.
toBeCloseTo
Added in: v1.9比较浮点数是否近似相等。比较浮点数时,使用此方法代替 expect(value).toBe()。
¥Compares floating point numbers for approximate equality. Use this method instead of expect(value).toBe() when comparing floating point numbers.
用法
¥Usage
expect(0.1 + 0.2).not.toBe(0.3);
expect(0.1 + 0.2).toBeCloseTo(0.3, 5);
参数
¥Arguments
期望值。
¥Expected value.
小数点后的小数位数必须相等。
¥The number of decimal digits after the decimal point that must be equal.
toBeDefined
Added in: v1.9确保该值不是 undefined
。
¥Ensures that value is not undefined
.
用法
¥Usage
const value = null;
expect(value).toBeDefined();
toBeFalsy
Added in: v1.9确保值在布尔上下文(false
、0
、''
、null
、undefined
或 NaN
之一)中为 false。当你不关心具体值时使用此方法。
¥Ensures that value is false in a boolean context, one of false
, 0
, ''
, null
, undefined
or NaN
. Use this method when you don't care about the specific value.
用法
¥Usage
const value = null;
expect(value).toBeFalsy();
toBeGreaterThan
Added in: v1.9确保 value > expected
代表数字或大整数值。
¥Ensures that value > expected
for number or big integer values.
用法
¥Usage
const value = 42;
expect(value).toBeGreaterThan(1);
参数
¥Arguments
要比较的值。
¥The value to compare to.
toBeGreaterThanOrEqual
Added in: v1.9确保 value >= expected
代表数字或大整数值。
¥Ensures that value >= expected
for number or big integer values.
用法
¥Usage
const value = 42;
expect(value).toBeGreaterThanOrEqual(42);
参数
¥Arguments
要比较的值。
¥The value to compare to.
toBeInstanceOf
Added in: v1.9确保该值是类的实例。使用 instanceof
运算符。
¥Ensures that value is an instance of a class. Uses instanceof
operator.
用法
¥Usage
expect(page).toBeInstanceOf(Page);
class Example {}
expect(new Example()).toBeInstanceOf(Example);
参数
¥Arguments
类或构造函数。
¥The class or constructor function.
toBeLessThan
Added in: v1.9确保 value < expected
代表数字或大整数值。
¥Ensures that value < expected
for number or big integer values.
用法
¥Usage
const value = 42;
expect(value).toBeLessThan(100);
参数
¥Arguments
要比较的值。
¥The value to compare to.
toBeLessThanOrEqual
Added in: v1.9确保 value <= expected
代表数字或大整数值。
¥Ensures that value <= expected
for number or big integer values.
用法
¥Usage
const value = 42;
expect(value).toBeLessThanOrEqual(42);
参数
¥Arguments
要比较的值。
¥The value to compare to.
toBeNaN
Added in: v1.9确保该值为 NaN
。
¥Ensures that value is NaN
.
用法
¥Usage
const value = NaN;
expect(value).toBeNaN();
toBeNull
Added in: v1.9确保该值为 null
。
¥Ensures that value is null
.
用法
¥Usage
const value = null;
expect(value).toBeNull();
toBeTruthy
Added in: v1.9确保该值在布尔上下文中为 true,但 false
、0
、''
、null
、undefined
或 NaN
除外。当你不关心具体值时使用此方法。
¥Ensures that value is true in a boolean context, anything but false
, 0
, ''
, null
, undefined
or NaN
. Use this method when you don't care about the specific value.
用法
¥Usage
const value = { example: 'value' };
expect(value).toBeTruthy();
toBeUndefined
Added in: v1.9确保该值为 undefined
。
¥Ensures that value is undefined
.
用法
¥Usage
const value = undefined;
expect(value).toBeUndefined();
toContain(expected)
Added in: v1.9确保字符串值包含预期的子字符串。比较区分大小写。
¥Ensures that string value contains an expected substring. Comparison is case-sensitive.
用法
¥Usage
const value = 'Hello, World';
expect(value).toContain('World');
expect(value).toContain(',');
参数
¥Arguments
预期的子串。
¥Expected substring.
toContain(expected)
Added in: v1.9确保该值为 Array
或 Set
并且包含预期项目。
¥Ensures that value is an Array
or Set
and contains an expected item.
用法
¥Usage
const value = [1, 2, 3];
expect(value).toContain(2);
expect(new Set(value)).toContain(2);
参数
¥Arguments
集合中的期望值。。
¥Expected value in the collection.
toContainEqual
Added in: v1.9确保该值是 Array
或 Set
并且包含等于预期的项目。
¥Ensures that value is an Array
or Set
and contains an item equal to the expected.
对于对象,此方法递归地检查所有字段的相等性,而不是像 expect(value).toContain() 那样通过引用比较对象。
¥For objects, this method recursively checks equality of all fields, rather than comparing objects by reference as performed by expect(value).toContain().
对于原始值,此方法相当于 expect(value).toContain()。
¥For primitive values, this method is equivalent to expect(value).toContain().
用法
¥Usage
const value = [
{ example: 1 },
{ another: 2 },
{ more: 3 },
];
expect(value).toContainEqual({ another: 2 });
expect(new Set(value)).toContainEqual({ another: 2 });
参数
¥Arguments
集合中的期望值。。
¥Expected value in the collection.
toEqual
Added in: v1.9将值的内容与 expected 的内容进行比较,执行 "深度平等" 检查。
¥Compares contents of the value with contents of expected, performing "deep equality" check.
对于对象,此方法递归地检查所有字段的相等性,而不是像 expect(value).toBe() 那样通过引用比较对象。
¥For objects, this method recursively checks equality of all fields, rather than comparing objects by reference as performed by expect(value).toBe().
对于原始值,此方法相当于 expect(value).toBe()。
¥For primitive values, this method is equivalent to expect(value).toBe().
用法
¥Usage
const value = { prop: 1 };
expect(value).toEqual({ prop: 1 });
非严格相等
¥Non-strict equality
expect(value).toEqual() 执行深度相等检查,比较接收值和预期值的内容。要确保两个对象引用同一实例,请改用 expect(value).toBe()。
¥expect(value).toEqual() performs deep equality check that compares contents of the received and expected values. To ensure two objects reference the same instance, use expect(value).toBe() instead.
expect(value).toEqual() 忽略 undefined
属性和数组项,并且不坚持对象类型相等。如需更严格的匹配,请使用 expect(value).toStrictEqual()。
¥expect(value).toEqual() ignores undefined
properties and array items, and does not insist on object types being equal. For stricter matching, use expect(value).toStrictEqual().
模式匹配
¥Pattern matching
借助以下匹配器,expect(value).toEqual() 还可用于对对象、数组和基本类型执行模式匹配:
¥expect(value).toEqual() can be also used to perform pattern matching on objects, arrays and primitive types, with the help of the following matchers:
下面是一个断言复杂对象内的一些值的示例:
¥Here is an example that asserts some of the values inside a complex object:
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') }),
}));
参数
¥Arguments
期望值。
¥Expected value.
toHaveLength
Added in: v1.9确保值的 .length
属性等于 expected。对于数组和字符串很有用。
¥Ensures that value has a .length
property equal to expected. Useful for arrays and strings.
用法
¥Usage
expect('Hello, World').toHaveLength(12);
expect([1, 2, 3]).toHaveLength(3);
参数
¥Arguments
预期长度。
¥Expected length.
toHaveProperty
Added in: v1.9确保对象上存在提供的 keyPath
处的属性,并可选择检查该属性是否等于 expected。与 expect(value).toEqual() 类似,递归地检查相等性。
¥Ensures that property at provided keyPath
exists on the object and optionally checks that property is equal to the expected. Equality is checked recursively, similarly to expect(value).toEqual().
用法
¥Usage
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);
参数
¥Arguments
属性的路径。使用点符号 a.b
检查嵌套属性,使用索引 a[2]
符号检查嵌套数组项。
¥Path to the property. Use dot notation a.b
to check nested properties and indexed a[2]
notation to check nested array items.
用于与属性进行比较的可选预期值。
¥Optional expected value to compare the property to.
toMatch
Added in: v1.9确保字符串值与正则表达式匹配。
¥Ensures that string value matches a regular expression.
用法
¥Usage
const value = 'Is 42 enough?';
expect(value).toMatch(/Is \d+ enough/);
参数
¥Arguments
要匹配的正则表达式。
¥Regular expression to match against.
toMatchObject
Added in: v1.9将值的内容与 expected 的内容进行比较,执行 "深度平等" 检查。与 expect(value).toEqual() 不同,允许值中存在额外的属性,因此你可以仅检查对象属性的子集。
¥Compares contents of the value with contents of expected, performing "deep equality" check. Allows extra properties to be present in the value, unlike expect(value).toEqual(), so you can check just a subset of object properties.
比较数组时,项目数必须匹配,并且递归检查每个项目。
¥When comparing arrays, the number of items must match, and each item is checked recursively.
用法
¥Usage
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 }]);
参数
¥Arguments
要匹配的预期对象值。
¥The expected object value to match against.
toStrictEqual
Added in: v1.9将值的内容与 expected 的内容及其类型进行比较。
¥Compares contents of the value with contents of expected and their types.
与 expect(value).toEqual() 的区别:
¥Differences from expect(value).toEqual():
-
检查具有未定义属性的键。例如,
{ a: undefined, b: 2 }
与{ b: 2 }
不匹配。¥Keys with undefined properties are checked. For example,
{ a: undefined, b: 2 }
does not match{ b: 2 }
. -
检查数组稀疏性。例如,
[, 1]
与[undefined, 1]
不匹配。¥Array sparseness is checked. For example,
[, 1]
does not match[undefined, 1]
. -
检查对象类型是否相等。例如,具有字段
a
和b
的类实例不等于具有字段a
和b
的字面量对象。¥Object types are checked to be equal. For example, a class instance with fields
a
andb
will not equal a literal object with fieldsa
andb
.
用法
¥Usage
const value = { prop: 1 };
expect(value).toStrictEqual({ prop: 1 });
参数
¥Arguments
期望值。
¥Expected value.
toThrow
Added in: v1.9调用该函数并确保它抛出错误。
¥Calls the function and ensures it throws an error.
(可选)将错误与 expected 进行比较。允许的期望值:
¥Optionally compares the error with expected. Allowed expected values:
-
正则表达式 - 错误消息应该与模式匹配。
¥Regular expression - error message should match the pattern.
-
字符串 - 错误消息应包含子字符串。
¥String - error message should include the substring.
-
错误对象 - 错误消息应该等于对象的消息属性。
¥Error object - error message should be equal to the message property of the object.
-
错误等级 - 错误对象应该是该类的实例。
¥Error class - error object should be an instance of the class.
用法
¥Usage
expect(() => {
throw new Error('Something bad');
}).toThrow();
expect(() => {
throw new Error('Something bad');
}).toThrow(/something/);
expect(() => {
throw new Error('Something bad');
}).toThrow(Error);
参数
¥Arguments
预期的错误消息或错误对象。
¥Expected error message or error object.
toThrowError
Added in: v1.9¥An alias for expect(value).toThrow().
用法
¥Usage
expect(() => {
throw new Error('Something bad');
}).toThrowError();
参数
¥Arguments
预期的错误消息或错误对象。
¥Expected error message or error object.
属性
¥Properties
not
Added in: v1.9使断言检查相反的条件。例如,以下代码通过:
¥Makes the assertion check for the opposite condition. For example, the following code passes:
const value = 1;
expect(value).not.toBe(2);
用法
¥Usage
expect(value).not
类型
¥Type