跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

GenericAssertions ​

Added in: v1.9

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 playwrightAssertions.expect():

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

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

Methods ​

genericAssertions.any() ​

Added in: v1.9

expect.any() matches any object instance created from the constructor or a corresponding primitive type. Use it inside genericAssertions.toEqual() to perform pattern matching.

Usage

js
// 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

  • constructor Function

    Constructor of the expected object like ExampleClass, or a primitive boxed type like Number.

genericAssertions.anything() ​

Added in: v1.9

expect.anything() matches everything except null and undefined. Use it inside genericAssertions.toEqual() to perform pattern matching.

Usage

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

genericAssertions.arrayContaining() ​

Added in: v1.9

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.

Use this method inside genericAssertions.toEqual() to perform pattern matching.

Usage

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

Arguments

  • expected Array<any>

    Expected array that is a subset of the received value.

genericAssertions.arrayOf() ​

Added in: v1.57

expect.arrayOf() matches array of objects created from the constructor or a corresponding primitive type. Use it inside genericAssertions.toEqual() to perform pattern matching.

Usage

js
// Match instance of a class.
class Example {}
expect([new Example(), new Example()]).toEqual(expect.arrayOf(Example));

// Match any string.
expect(['a', 'b', 'c']).toEqual(expect.arrayOf(String));

Arguments

  • constructor Function

    Constructor of the expected object like ExampleClass, or a primitive boxed type like Number.

genericAssertions.closeTo() ​

Added in: v1.9

Compares floating point numbers for approximate equality. Use this method inside genericAssertions.toEqual() to perform pattern matching. When just comparing two numbers, prefer genericAssertions.toBeCloseTo().

Usage

js
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 float

    Expected value.

  • numDigits int (optional)

    The number of decimal digits after the decimal point that must be equal.

genericAssertions.objectContaining() ​

Added in: v1.9

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.

Use this method inside genericAssertions.toEqual() to perform pattern matching. Object properties can be matchers to further relax the expectation. See examples.

Usage

js
// 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

    Expected object pattern that contains a subset of the properties.

genericAssertions.stringContaining() ​

Added in: v1.9

expect.stringContaining() matches a string that contains the expected substring. Use this method inside genericAssertions.toEqual() to perform pattern matching.

Usage

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

Arguments

  • expected string

    Expected substring.

genericAssertions.stringMatching() ​

Added in: v1.9

expect.stringMatching() matches a received string that in turn matches the expected pattern. Use this method inside genericAssertions.toEqual() to perform pattern matching.

Usage

js
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

  • expected string | RegExp

    Pattern that expected string should match.

genericAssertions.toBe() ​

Added in: v1.9

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

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

Arguments

  • expected any

    Expected value.

genericAssertions.toBeCloseTo() ​

Added in: v1.9

Compares floating point numbers for approximate equality. Use this method instead of genericAssertions.toBe() when comparing floating point numbers.

Usage

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

Arguments

  • expected float

    Expected value.

  • numDigits int (optional)

    The number of decimal digits after the decimal point that must be equal.

genericAssertions.toBeDefined() ​

Added in: v1.9

Ensures that value is not undefined.

Usage

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

genericAssertions.toBeFalsy() ​

Added in: v1.9

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

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

genericAssertions.toBeGreaterThan() ​

Added in: v1.9

Ensures that value > expected for number or big integer values.

Usage

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

Arguments

  • expected float | bigint

    The value to compare to.

genericAssertions.toBeGreaterThanOrEqual() ​

Added in: v1.9

Ensures that value >= expected for number or big integer values.

Usage

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

Arguments

  • expected float | bigint

    The value to compare to.

genericAssertions.toBeInstanceOf() ​

Added in: v1.9

Ensures that value is an instance of a class. Uses instanceof operator.

Usage

js
expect(page).toBeInstanceOf(Page);

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

Arguments

  • expected Function

    The class or constructor function.

genericAssertions.toBeLessThan() ​

Added in: v1.9

Ensures that value < expected for number or big integer values.

Usage

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

Arguments

  • expected float | bigint

    The value to compare to.

genericAssertions.toBeLessThanOrEqual() ​

Added in: v1.9

Ensures that value <= expected for number or big integer values.

Usage

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

Arguments

  • expected float | bigint

    The value to compare to.

genericAssertions.toBeNaN() ​

Added in: v1.9

Ensures that value is NaN.

Usage

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

genericAssertions.toBeNull() ​

Added in: v1.9

Ensures that value is null.

Usage

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

genericAssertions.toBeTruthy() ​

Added in: v1.9

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

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

genericAssertions.toBeUndefined() ​

Added in: v1.9

Ensures that value is undefined.

Usage

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

genericAssertions.toContain() ​

Added in: v1.9

Ensures that string value contains an expected substring. Comparison is case-sensitive.

Usage

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

Arguments

  • expected string

    Expected substring.

genericAssertions.toContain() ​

Added in: v1.9

Ensures that value is an Array or Set and contains an expected item.

Usage

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

Arguments

  • expected any

    Expected value in the collection.

genericAssertions.toContainEqual() ​

Added in: v1.9

Ensures that value is an Array or Set and contains an item equal to the expected.

For objects, this method recursively checks equality of all fields, rather than comparing objects by reference as performed by genericAssertions.toContain().

For primitive values, this method is equivalent to genericAssertions.toContain().

Usage

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

Arguments

  • expected any

    Expected value in the collection.

genericAssertions.toEqual() ​

Added in: v1.9

Compares contents of the value with contents of expected, performing "deep equality" check.

For objects, this method recursively checks equality of all fields, rather than comparing objects by reference as performed by genericAssertions.toBe().

For primitive values, this method is equivalent to genericAssertions.toBe().

Usage

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

Non-strict equality

genericAssertions.toEqual() performs deep equality check that compares contents of the received and expected values. To ensure two objects reference the same instance, use genericAssertions.toBe() instead.

genericAssertions.toEqual() ignores undefined properties and array items, and does not insist on object types being equal. For stricter matching, use genericAssertions.toStrictEqual().

Pattern matching

genericAssertions.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:

js
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 any

    Expected value.

genericAssertions.toHaveLength() ​

Added in: v1.9

Ensures that value has a .length property equal to expected. Useful for arrays and strings.

Usage

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

Arguments

  • expected int

    Expected length.

genericAssertions.toHaveProperty() ​

Added in: v1.9

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 genericAssertions.toEqual().

Usage

js
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

  • keyPath string

    Path to the property. Use dot notation a.b to check nested properties and indexed a[2] notation to check nested array items.

  • expected any (optional)

    Optional expected value to compare the property to.

genericAssertions.toMatch() ​

Added in: v1.9

Ensures that string value matches a regular expression.

Usage

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

Arguments

  • expected RegExp | string

    Regular expression to match against.

genericAssertions.toMatchObject() ​

Added in: v1.9

Compares contents of the value with contents of expected, performing "deep equality" check. Allows extra properties to be present in the value, unlike genericAssertions.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

js
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

  • expected Object | Array

    The expected object value to match against.

genericAssertions.toStrictEqual() ​

Added in: v1.9

Compares contents of the value with contents of expected and their types.

Differences from genericAssertions.toEqual():

  • Keys with undefined properties are checked. For example, { a: undefined, b: 2 } does not match { b: 2 }.
  • Array sparseness is checked. For example, [, 1] does not match [undefined, 1].
  • Object types are checked to be equal. For example, a class instance with fields a and b will not equal a literal object with fields a and b.

Usage

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

Arguments

  • expected any

    Expected value.

genericAssertions.toThrow() ​

Added in: v1.9

Calls the function and ensures it throws an error.

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

js
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 any (optional)

    Expected error message or error object.

genericAssertions.toThrowError() ​

Added in: v1.9

An alias for genericAssertions.toThrow().

Usage

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

Arguments

  • expected any (optional)

    Expected error message or error object.

Properties ​

genericAssertions.not ​

Added in: v1.9

Makes the assertion check for the opposite condition.

Usage

For example, the following code passes:

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

Type

  • GenericAssertions

genericAssertions.rejects ​

Added in: v1.9

Use .rejects to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.

For example, this code tests that the promise rejects with reason 'octopus':

js
test('rejects to octopus', async () => {
  await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});

Type

  • GenericAssertions

genericAssertions.resolves ​

Added in: v1.9

Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails.

For example, this code tests that the promise resolves and that the resulting value is 'lemon':

js
test('resolves to lemon', async () => {
  await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});

Type

  • GenericAssertions

基于 Apache 2.0 许可证发布。