assert
O Vitest reexporta o método assert de chai para verificar invariantes.
assert
- Tipo:
(expression: any, message?: string) => asserts expression
Afirma que a expression fornecida é truthy. Caso contrário, a asserção falha.
import { assert, test } from 'vitest';
test('assert', () => {
assert('foo' !== 'bar', 'foo não deveria ser igual a bar');
});fail
- Tipo:
(message?: string) => never<T>(actual: T, expected: T, message?: string, operator?: string) => never
Força a falha de uma asserção.
import { assert, test } from 'vitest';
test('assert.fail', () => {
assert.fail('mensagem de erro em caso de falha');
assert.fail('foo', 'bar', 'foo não é bar', '===');
});isOk
- Tipo:
<T>(value: T, message?: string) => void - Alias:
ok
Afirma que o value fornecido é truthy.
import { assert, test } from 'vitest';
test('assert.isOk', () => {
assert.isOk('foo', 'toda expressão verdadeira é válida');
assert.isOk(false, 'isso falhará porque false não é truthy');
});isNotOk
- Tipo:
<T>(value: T, message?: string) => void - Alias:
notOk
Afirma que o value fornecido é falsy.
import { assert, test } from 'vitest';
test('assert.isNotOk', () => {
assert.isNotOk('foo', 'toda expressão verdadeira não é válida');
assert.isNotOk(false, 'isso passará porque false é falsy');
});equal
- Tipo:
<T>(actual: T, expected: T, message?: string) => void
Afirma a igualdade não estrita (==) entre actual e expected.
import { assert, test } from 'vitest';
test('assert.equal', () => {
assert.equal(Math.sqrt(4), '2');
});notEqual
- Tipo:
<T>(actual: T, expected: T, message?: string) => void
Afirma a desigualdade não estrita (!=) entre actual e expected.
import { assert, test } from 'vitest';
test('assert.equal', () => {
assert.notEqual(Math.sqrt(4), 3);
});strictEqual
- Tipo:
<T>(actual: T, expected: T, message?: string) => void
Afirma a igualdade estrita (===) entre actual e expected.
import { assert, test } from 'vitest';
test('assert.strictEqual', () => {
assert.strictEqual(Math.sqrt(4), 2);
});deepEqual
- Tipo:
<T>(actual: T, expected: T, message?: string) => void
Afirma que actual é profundamente igual a expected.
import { assert, test } from 'vitest';
test('assert.deepEqual', () => {
assert.deepEqual({ color: 'green' }, { color: 'green' });
});notDeepEqual
- Tipo:
<T>(actual: T, expected: T, message?: string) => void
Afirma que actual não é profundamente igual a expected.
import { assert, test } from 'vitest';
test('assert.notDeepEqual', () => {
assert.notDeepEqual({ color: 'green' }, { color: 'red' });
});isAbove
- Tipo:
(valueToCheck: number, valueToBeAbove: number, message?: string) => void
Afirma que valueToCheck é estritamente maior que valueToBeAbove.
import { assert, test } from 'vitest';
test('assert.isAbove', () => {
assert.isAbove(5, 2, '5 é estritamente maior que 2');
});isAtLeast
- Tipo:
(valueToCheck: number, valueToBeAtLeast: number, message?: string) => void
Afirma que valueToCheck é maior ou igual a valueToBeAtLeast.
import { assert, test } from 'vitest';
test('assert.isAtLeast', () => {
assert.isAtLeast(5, 2, '5 é maior ou igual a 2');
assert.isAtLeast(3, 3, '3 é maior ou igual a 3');
});isBelow
- Tipo:
(valueToCheck: number, valueToBeBelow: number, message?: string) => void
Afirma que valueToCheck é estritamente menor que valueToBeBelow.
import { assert, test } from 'vitest';
test('assert.isBelow', () => {
assert.isBelow(3, 6, '3 é estritamente menor que 6');
});isAtMost
- Tipo:
(valueToCheck: number, valueToBeAtMost: number, message?: string) => void
Afirma que valueToCheck é menor ou igual a valueToBeAtMost.
import { assert, test } from 'vitest';
test('assert.isAtMost', () => {
assert.isAtMost(3, 6, '3 é menor ou igual a 6');
assert.isAtMost(4, 4, '4 é menor ou igual a 4');
});isTrue
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é true.
import { assert, test } from 'vitest';
const testPassed = true;
test('assert.isTrue', () => {
assert.isTrue(testPassed);
});isNotTrue
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é true.
import { assert, test } from 'vitest';
const testPassed = 'ok';
test('assert.isNotTrue', () => {
assert.isNotTrue(testPassed);
});isFalse
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é false.
import { assert, test } from 'vitest';
const testPassed = false;
test('assert.isFalse', () => {
assert.isFalse(testPassed);
});isNotFalse
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é false.
import { assert, test } from 'vitest';
const testPassed = 'no';
test('assert.isNotFalse', () => {
assert.isNotFalse(testPassed);
});isNull
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é null.
import { assert, test } from 'vitest';
const error = null;
test('assert.isNull', () => {
assert.isNull(error, 'error é nulo');
});isNotNull
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é null.
import { assert, test } from 'vitest';
const error = { message: 'error was occured' };
test('assert.isNotNull', () => {
assert.isNotNull(error, 'o erro não é nulo, mas um objeto');
});isNaN
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é NaN.
import { assert, test } from 'vitest';
const calculation = 1 * 'viitest';
test('assert.isNaN', () => {
assert.isNaN(calculation, '1 * "vitest" é NaN');
});isNotNaN
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é NaN.
import { assert, test } from 'vitest';
const calculation = 1 * 2;
test('assert.isNotNaN', () => {
assert.isNotNaN(calculation, '1 * 2 não é NaN, e sim 2');
});exists
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é null nem undefined.
import { assert, test } from 'vitest';
const name = 'foo';
test('assert.exists', () => {
assert.exists(name, 'foo não é nulo nem indefinido');
});notExists
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é null ou undefined.
import { assert, test } from 'vitest';
const foo = null;
const bar = undefined;
test('assert.notExists', () => {
assert.notExists(foo, 'foo é nulo, portanto não existe');
assert.notExists(bar, 'bar é indefinido, então não existe');
});isUndefined
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é undefined.
import { assert, test } from 'vitest';
const name = undefined;
test('assert.isUndefined', () => {
assert.isUndefined(name, 'name é indefinido');
});isDefined
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é undefined.
import { assert, test } from 'vitest';
const name = 'foo';
test('assert.isDefined', () => {
assert.isDefined(name, 'name não é indefinido');
});isFunction
- Tipo:
<T>(value: T, message?: string) => void - Alias:
isCallableAfirma quevalueé uma função.
import { assert, test } from 'vitest';
function name() {
return 'foo';
}
test('assert.isFunction', () => {
assert.isFunction(name, 'name é uma função');
});isNotFunction
- Tipo:
<T>(value: T, message?: string) => void - Alias:
isNotCallable
Afirma que value não é uma função.
import { assert, test } from 'vitest';
const name = 'foo';
test('assert.isNotFunction', () => {
assert.isNotFunction(name, 'name não é uma função, mas sim uma string');
});isObject
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é um objeto do tipo Object (conforme revelado por Object.prototype.toString). A asserção não corresponde a objetos subclassificados.
import { assert, test } from 'vitest';
const someThing = { color: 'red', shape: 'circle' };
test('assert.isObject', () => {
assert.isObject(someThing, 'someThing é um objeto');
});isNotObject
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é um objeto do tipo Object (determinado por Object.prototype.toString). A asserção não se aplica a objetos de subclasses.
import { assert, test } from 'vitest';
const someThing = 'redCircle';
test('assert.isNotObject', () => {
assert.isNotObject(someThing, 'someThing não é um objeto, é uma string');
});isArray
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é um array.
import { assert, test } from 'vitest';
const color = ['red', 'green', 'yellow'];
test('assert.isArray', () => {
assert.isArray(color, 'color é um array');
});isNotArray
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é um array.
import { assert, test } from 'vitest';
const color = 'red';
test('assert.isNotArray', () => {
assert.isNotArray(color, 'color não é um array, é uma string');
});isString
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é uma string.
import { assert, test } from 'vitest';
const color = 'red';
test('assert.isString', () => {
assert.isString(color, 'color é uma string');
});isNotString
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é uma string.
import { assert, test } from 'vitest';
const color = ['red', 'green', 'yellow'];
test('assert.isNotString', () => {
assert.isNotString(color, 'color não é uma string, é um array');
});isNumber
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é um número.
import { assert, test } from 'vitest';
const colors = 3;
test('assert.isNumber', () => {
assert.isNumber(colors, 'colors é um número');
});isNotNumber
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é um número.
import { assert, test } from 'vitest';
const colors = '3 colors';
test('assert.isNotNumber', () => {
assert.isNotNumber(colors, 'colors não é um número, é uma string');
});isFinite
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é um número finito (não NaN, nem Infinity).
import { assert, test } from 'vitest';
const colors = 3;
test('assert.isFinite', () => {
assert.isFinite(colors, 'colors é um número finito, não NaN ou Infinity');
});isBoolean
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value é um booleano.
import { assert, test } from 'vitest';
const isReady = true;
test('assert.isBoolean', () => {
assert.isBoolean(isReady, 'isReady é um valor booleano');
});isNotBoolean
- Tipo:
<T>(value: T, message?: string) => void
Afirma que value não é um booleano.
import { assert, test } from 'vitest';
const isReady = 'sure';
test('assert.isBoolean', () => {
assert.isBoolean(isReady, 'isReady não é um booleano, é uma string');
});typeOf
- Tipo:
<T>(value: T, name: string, message?: string) => void
Afirma que o tipo de value é name, conforme determinado por Object.prototype.toString.
import { assert, test } from 'vitest';
test('assert.typeOf', () => {
assert.typeOf({ color: 'red' }, 'object', 'temos um objeto');
assert.typeOf(['red', 'green'], 'array', 'temos um array');
assert.typeOf('red', 'string', 'temos uma string');
assert.typeOf(/red/, 'regexp', 'temos uma expressão regular');
assert.typeOf(null, 'null', 'temos null');
assert.typeOf(undefined, 'undefined', 'temos undefined');
});notTypeOf
- Tipo:
<T>(value: T, name: string, message?: string) => void
Afirma que o tipo de value não é name, conforme determinado por Object.prototype.toString.
import { assert, test } from 'vitest';
test('assert.notTypeOf', () => {
assert.notTypeOf('red', 'number', '"red" não é um número');
});instanceOf
- Tipo:
<T>(value: T, constructor: Function, message?: string) => void
Afirma que value é uma instância de constructor.
import { assert, test } from 'vitest';
function Person(name) {
this.name = name;
}
const foo = new Person('foo');
class Tea {
constructor(name) {
this.name = name;
}
}
const coffee = new Tea('coffee');
test('assert.instanceOf', () => {
assert.instanceOf(foo, Person, 'foo é uma instância de Person');
assert.instanceOf(coffee, Tea, 'coffee é uma instância de Tea');
});notInstanceOf
- Tipo:
<T>(value: T, constructor: Function, message?: string) => void
Afirma que value não é uma instância de constructor.
import { assert, test } from 'vitest';
function Person(name) {
this.name = name;
}
const foo = new Person('foo');
class Tea {
constructor(name) {
this.name = name;
}
}
const coffee = new Tea('coffee');
test('assert.instanceOf', () => {
assert.instanceOf(foo, Tea, 'foo não é uma instância de Tea');
});include
- Tipo:
(haystack: string, needle: string, message?: string) => void<T>(haystack: readonly T[] | ReadonlySet<T> | ReadonlyMap<any, T>, needle: T, message?: string) => void<T extends object>(haystack: WeakSet<T>, needle: T, message?: string) => void<T>(haystack: T, needle: Partial<T>, message?: string) => void
Afirma que haystack inclui needle. Pode ser usado para verificar a inclusão de um valor em um array, uma substring em uma string ou um subconjunto de propriedades em um objeto.
import { assert, test } from 'vitest';
test('assert.include', () => {
assert.include([1, 2, 3], 2, 'array contém o valor');
assert.include('foobar', 'foo', 'string contém a substring');
assert.include(
{ foo: 'bar', hello: 'universe' },
{ foo: 'bar' },
'objeto contém a propriedade'
);
});notInclude
- Tipo:
(haystack: string, needle: string, message?: string) => void<T>(haystack: readonly T[] | ReadonlySet<T> | ReadonlyMap<any, T>, needle: T, message?: string) => void<T extends object>(haystack: WeakSet<T>, needle: T, message?: string) => void<T>(haystack: T, needle: Partial<T>, message?: string) => void
Afirma que haystack não inclui needle. Pode ser usado para verificar a ausência de um valor em um array, uma substring em uma string ou um subconjunto de propriedades em um objeto.
import { assert, test } from 'vitest';
test('assert.notInclude', () => {
assert.notInclude([1, 2, 3], 4, 'a lista não contém 4');
assert.notInclude('foobar', 'baz', 'foobar não tem baz');
assert.notInclude(
{ foo: 'bar', hello: 'universe' },
{ foo: 'baz' },
'objeto não contém a propriedade'
);
});deepInclude
- Tipo:
(haystack: string, needle: string, message?: string) => void<T>(haystack: readonly T[] | ReadonlySet<T> | ReadonlyMap<any, T>, needle: T, message?: string) => void<T>(haystack: T, needle: T extends WeakSet<any> ? never : Partial<T>, message?: string) => void
Afirma que haystack inclui needle. Pode ser usado para verificar a inclusão de um valor em um array ou um subconjunto de propriedades em um objeto. A igualdade profunda é utilizada.
import { assert, test } from 'vitest';
const obj1 = { a: 1 };
const obj2 = { b: 2 };
test('assert.deepInclude', () => {
assert.deepInclude([obj1, obj2], { a: 1 });
assert.deepInclude({ foo: obj1, bar: obj2 }, { foo: { a: 1 } });
});notDeepInclude
- Tipo:
(haystack: string, needle: string, message?: string) => void<T>(haystack: readonly T[] | ReadonlySet<T> | ReadonlyMap<any, T>, needle: T, message?: string) => void<T>(haystack: T, needle: T extends WeakSet<any> ? never : Partial<T>, message?: string) => void
Afirma que haystack não inclui needle. Pode ser usado para verificar a ausência de um valor em um array ou um subconjunto de propriedades em um objeto. A igualdade profunda é utilizada.
import { assert, test } from 'vitest';
const obj1 = { a: 1 };
const obj2 = { b: 2 };
test('assert.notDeepInclude', () => {
assert.notDeepInclude([obj1, obj2], { a: 10 });
assert.notDeepInclude({ foo: obj1, bar: obj2 }, { foo: { a: 10 } });
});nestedInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack inclui needle. Pode ser usado para verificar a inclusão de um subconjunto de propriedades em um objeto. Permite usar notação com ponto e colchetes para referenciar propriedades aninhadas. ‘[]’ e ‘.’ em nomes de propriedades podem ser escapados usando barras invertidas duplas (\\).
import { assert, test } from 'vitest';
test('assert.nestedInclude', () => {
assert.nestedInclude({ '.a': { b: 'x' } }, { '\\.a.[b]': 'x' });
assert.nestedInclude({ a: { '[b]': 'x' } }, { 'a.\\[b\\]': 'x' });
});notNestedInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack não inclui needle. Pode ser usado para verificar a ausência de um subconjunto de propriedades em um objeto. Permite usar notação com ponto e colchetes para referenciar propriedades aninhadas. ‘[]’ e ‘.’ em nomes de propriedades podem ser escapados usando barras invertidas duplas (\\).
import { assert, test } from 'vitest';
test('assert.notNestedInclude', () => {
assert.notNestedInclude({ '.a': { b: 'x' } }, { '\\.a.b': 'y' });
assert.notNestedInclude({ a: { '[b]': 'x' } }, { 'a.\\[b\\]': 'y' });
});deepNestedInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack inclui needle. Pode ser usado para verificar a inclusão de um subconjunto de propriedades em um objeto, utilizando igualdade profunda. Permite usar notação com ponto e colchetes para referenciar propriedades aninhadas. ‘[]’ e ‘.’ em nomes de propriedades podem ser escapados usando barras invertidas duplas (\\).
import { assert, test } from 'vitest';
test('assert.deepNestedInclude', () => {
assert.deepNestedInclude({ a: { b: [{ x: 1 }] } }, { 'a.b[0]': { x: 1 } });
assert.deepNestedInclude(
{ '.a': { '[b]': { x: 1 } } },
{ '\\.a.\\[b\\]': { x: 1 } }
);
});notDeepNestedInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack não inclui needle. Pode ser usado para verificar a ausência de um subconjunto de propriedades em um objeto, utilizando igualdade profunda. Permite usar notação com ponto e colchetes para referenciar propriedades aninhadas. ‘[]’ e ‘.’ em nomes de propriedades podem ser escapados usando barras invertidas duplas (\\).
import { assert, test } from 'vitest';
test('assert.notDeepNestedInclude', () => {
assert.notDeepNestedInclude({ a: { b: [{ x: 1 }] } }, { 'a.b[0]': { y: 1 } });
assert.notDeepNestedInclude(
{ '.a': { '[b]': { x: 1 } } },
{ '\\.a.\\[b\\]': { y: 2 } }
);
});ownInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack inclui needle. Pode ser usado para verificar a inclusão de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas.
import { assert, test } from 'vitest';
test('assert.ownInclude', () => {
assert.ownInclude({ a: 1 }, { a: 1 });
});notOwnInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Afirma que haystack não inclui needle. Pode ser usado para verificar a ausência de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas.
import { assert, test } from 'vitest';
const obj1 = {
b: 2,
};
const obj2 = Object.create(obj1);
obj2.a = 1;
test('assert.notOwnInclude', () => {
assert.notOwnInclude(obj2, { b: 2 });
});deepOwnInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Verifica se haystack inclui needle. Pode ser usado para verificar a inclusão de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas e com verificação de igualdade profunda.
import { assert, test } from 'vitest';
test('assert.deepOwnInclude', () => {
assert.deepOwnInclude({ a: { b: 2 } }, { a: { b: 2 } });
});notDeepOwnInclude
- Tipo:
(haystack: any, needle: any, message?: string) => void
Verifica se haystack não inclui needle. Pode ser usado para verificar a ausência de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas e com verificação de igualdade profunda.
import { assert, test } from 'vitest';
test('assert.notDeepOwnInclude', () => {
assert.notDeepOwnInclude({ a: { b: 2 } }, { a: { c: 3 } });
});match
- Tipo:
(value: string, regexp: RegExp, message?: string) => void
Verifica se value corresponde à expressão regular regexp.
import { assert, test } from 'vitest';
test('assert.match', () => {
assert.match('foobar', /^foo/, 'regexp matches');
});notMatch
- Tipo:
(value: string, regexp: RegExp, message?: string) => void
Verifica se value não corresponde à expressão regular regexp.
import { assert, test } from 'vitest';
test('assert.notMatch', () => {
assert.notMatch('foobar', /^foo/, 'regexp does not match');
});property
- Tipo:
<T>(object: T, property: string, message?: string) => void
Verifica se object possui uma propriedade direta ou herdada com o nome especificado em property.
import { assert, test } from 'vitest';
test('assert.property', () => {
assert.property({ tea: { green: 'matcha' } }, 'tea');
assert.property({ tea: { green: 'matcha' } }, 'toString');
});notProperty
- Tipo:
<T>(object: T, property: string, message?: string) => void
Verifica se object não possui uma propriedade direta ou herdada com o nome especificado em property.
import { assert, test } from 'vitest';
test('assert.notProperty', () => {
assert.notProperty({ tea: { green: 'matcha' } }, 'coffee');
});propertyVal
- Tipo:
<T, V>(object: T, property: string, value: V, message?: string) => void
Verifica se object possui uma propriedade direta ou herdada com o nome especificado em property e se o valor dessa propriedade é estritamente igual (===) a value.
import { assert, test } from 'vitest';
test('assert.propertyVal', () => {
assert.propertyVal({ tea: 'is good' }, 'tea', 'is good');
});notPropertyVal
- Tipo:
<T, V>(object: T, property: string, value: V, message?: string) => void
Verifica se object não possui uma propriedade direta ou herdada com o nome especificado em property ou se o valor dessa propriedade não é estritamente igual (===) a value.
import { assert, test } from 'vitest';
test('assert.notPropertyVal', () => {
assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad');
assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good');
});deepPropertyVal
- Tipo:
<T, V>(object: T, property: string, value: V, message?: string) => void
Verifica se object possui uma propriedade direta ou herdada com o nome especificado em property e se o valor dessa propriedade é profundamente igual a value.
import { assert, test } from 'vitest';
test('assert.deepPropertyVal', () => {
assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', {
green: 'matcha',
});
});notDeepPropertyVal
- Tipo:
<T, V>(object: T, property: string, value: V, message?: string) => void
Verifica se object não possui uma propriedade direta ou herdada com o nome especificado em property ou se o valor dessa propriedade não é profundamente igual a value.
import { assert, test } from 'vitest';
test('assert.notDeepPropertyVal', () => {
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', {
black: 'matcha',
});
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', {
green: 'oolong',
});
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', {
green: 'matcha',
});
});nestedProperty
- Tipo:
<T>(object: T, property: string, message?: string) => void
Verifica se object possui uma propriedade direta ou herdada com o nome especificado em property, que pode ser uma string usando notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.nestedProperty', () => {
assert.nestedProperty({ tea: { green: 'matcha' } }, 'tea.green');
});notNestedProperty
- Tipo:
<T>(object: T, property: string, message?: string) => void
Verifica se object não possui uma propriedade direta ou herdada com o nome especificado em property, que pode ser uma string usando notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.notNestedProperty', () => {
assert.notNestedProperty({ tea: { green: 'matcha' } }, 'tea.oolong');
});nestedPropertyVal
- Tipo:
<T>(object: T, property: string, value: any, message?: string) => void
Verifica se object possui uma propriedade com o nome especificado em property e se o valor dessa propriedade é estritamente igual (===) a value. property pode usar notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.nestedPropertyVal', () => {
assert.nestedPropertyVal({ tea: { green: 'matcha' } }, 'tea.green', 'matcha');
});notNestedPropertyVal
- Tipo:
<T>(object: T, property: string, value: any, message?: string) => void
Verifica se object não possui uma propriedade com o nome especificado em property ou se o valor dessa propriedade não é estritamente igual (===) a value. property pode usar notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.notNestedPropertyVal', () => {
assert.notNestedPropertyVal(
{ tea: { green: 'matcha' } },
'tea.green',
'konacha'
);
assert.notNestedPropertyVal(
{ tea: { green: 'matcha' } },
'coffee.green',
'matcha'
);
});deepNestedPropertyVal
- Tipo:
<T>(object: T, property: string, value: any, message?: string) => void
Verifica se object possui uma propriedade com o nome especificado em property e se o valor dessa propriedade é profundamente igual a value. property pode usar notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.deepNestedPropertyVal', () => {
assert.deepNestedPropertyVal(
{ tea: { green: 'matcha' } },
'tea.green',
'konacha'
);
assert.deepNestedPropertyVal(
{ tea: { green: 'matcha' } },
'coffee.green',
'matcha'
);
});notDeepNestedPropertyVal
- Tipo:
<T>(object: T, property: string, value: any, message?: string) => void
Verifica se object não possui uma propriedade com o nome especificado em property ou se o valor dessa propriedade não é profundamente igual a value. property pode usar notação de ponto ou colchetes para referenciar propriedades aninhadas.
import { assert, test } from 'vitest';
test('assert.notDeepNestedPropertyVal', () => {
assert.notDeepNestedPropertyVal(
{ tea: { green: { matcha: 'yum' } } },
'tea.green',
{ oolong: 'yum' }
);
assert.notDeepNestedPropertyVal(
{ tea: { green: { matcha: 'yum' } } },
'tea.green',
{ matcha: 'yuck' }
);
assert.notDeepNestedPropertyVal(
{ tea: { green: { matcha: 'yum' } } },
'tea.black',
{ matcha: 'yum' }
);
});lengthOf
- Tipo:
<T extends { readonly length?: number | undefined } | { readonly size?: number | undefined }>(object: T, length: number, message?: string) => void
Verifica se object possui uma propriedade length ou size com o valor esperado.
import { assert, test } from 'vitest';
test('assert.lengthOf', () => {
assert.lengthOf([1, 2, 3], 3, 'array has length of 3');
assert.lengthOf('foobar', 6, 'string has length of 6');
assert.lengthOf(new Set([1, 2, 3]), 3, 'set has size of 3');
assert.lengthOf(
new Map([
['a', 1],
['b', 2],
['c', 3],
]),
3,
'map has size of 3'
);
});hasAnyKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Verifica se object possui pelo menos uma das chaves especificadas em keys. Você também pode fornecer um único objeto em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.hasAnyKeys', () => {
assert.hasAnyKeys({ foo: 1, bar: 2, baz: 3 }, ['foo', 'iDontExist', 'baz']);
assert.hasAnyKeys(
{ foo: 1, bar: 2, baz: 3 },
{ foo: 30, iDontExist: 99, baz: 1337 }
);
assert.hasAnyKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ foo: 1 }, 'key']
);
assert.hasAnyKeys(new Set([{ foo: 'bar' }, 'anotherKey']), [
{ foo: 'bar' },
'anotherKey',
]);
});hasAllKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Verifica se object possui todas as chaves fornecidas em keys e somente elas. Você também pode fornecer um único objeto em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.hasAllKeys', () => {
assert.hasAllKeys({ foo: 1, bar: 2, baz: 3 }, ['foo', 'bar', 'baz']);
assert.hasAllKeys(
{ foo: 1, bar: 2, baz: 3 },
{ foo: 30, bar: 99, baz: 1337 }
);
assert.hasAllKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ foo: 1 }, 'key']
);
assert.hasAllKeys(
new Set([{ foo: 'bar' }, 'anotherKey'], [{ foo: 'bar' }, 'anotherKey'])
);
});containsAllKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Verifica se object contém todas as chaves fornecidas em keys, mas pode conter outras chaves além das listadas. Você também pode fornecer um único objeto em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.containsAllKeys', () => {
assert.containsAllKeys({ foo: 1, bar: 2, baz: 3 }, ['foo', 'baz']);
assert.containsAllKeys({ foo: 1, bar: 2, baz: 3 }, ['foo', 'bar', 'baz']);
assert.containsAllKeys({ foo: 1, bar: 2, baz: 3 }, { foo: 30, baz: 1337 });
assert.containsAllKeys(
{ foo: 1, bar: 2, baz: 3 },
{ foo: 30, bar: 99, baz: 1337 }
);
assert.containsAllKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ foo: 1 }]
);
assert.containsAllKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ foo: 1 }, 'key']
);
assert.containsAllKeys(
new Set([{ foo: 'bar' }, 'anotherKey'], [{ foo: 'bar' }])
);
assert.containsAllKeys(
new Set([{ foo: 'bar' }, 'anotherKey'], [{ foo: 'bar' }, 'anotherKey'])
);
});doesNotHaveAnyKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object não possui nenhuma das keys fornecidas. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.doesNotHaveAnyKeys', () => {
assert.doesNotHaveAnyKeys({ foo: 1, bar: 2, baz: 3 }, [
'one',
'two',
'example',
]);
assert.doesNotHaveAnyKeys(
{ foo: 1, bar: 2, baz: 3 },
{ one: 1, two: 2, example: 'foo' }
);
assert.doesNotHaveAnyKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ one: 'two' }, 'example']
);
assert.doesNotHaveAnyKeys(
new Set([{ foo: 'bar' }, 'anotherKey'], [{ one: 'two' }, 'example'])
);
});doesNotHaveAllKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object não possui pelo menos uma das keys fornecidas. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.doesNotHaveAllKeys', () => {
assert.doesNotHaveAnyKeys({ foo: 1, bar: 2, baz: 3 }, [
'one',
'two',
'example',
]);
assert.doesNotHaveAnyKeys(
{ foo: 1, bar: 2, baz: 3 },
{ one: 1, two: 2, example: 'foo' }
);
assert.doesNotHaveAnyKeys(
new Map([
[{ foo: 1 }, 'bar'],
['key', 'value'],
]),
[{ one: 'two' }, 'example']
);
assert.doesNotHaveAnyKeys(new Set([{ foo: 'bar' }, 'anotherKey']), [
{ one: 'two' },
'example',
]);
});hasAnyDeepKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object possui pelo menos uma das keys fornecidas. Como Sets e Maps podem ter objetos como chaves, você pode usar esta asserção para realizar uma comparação profunda. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.hasAnyDeepKeys', () => {
assert.hasAnyDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[1, 2],
]),
{ one: 'one' }
);
assert.hasAnyDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[1, 2],
]),
[{ one: 'one' }, { two: 'two' }]
);
assert.hasAnyDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[{ two: 'two' }, 'valueTwo'],
]),
[{ one: 'one' }, { two: 'two' }]
);
assert.hasAnyDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), {
one: 'one',
});
assert.hasAnyDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ one: 'one' },
{ three: 'three' },
]);
assert.hasAnyDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ one: 'one' },
{ two: 'two' },
]);
});hasAllDeepKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object possui todas as keys fornecidas. Como Sets e Maps podem ter objetos como chaves, você pode usar esta asserção para realizar uma comparação profunda. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.hasAllDeepKeys', () => {
assert.hasAllDeepKeys(new Map([[{ one: 'one' }, 'valueOne']]), {
one: 'one',
});
assert.hasAllDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[{ two: 'two' }, 'valueTwo'],
]),
[{ one: 'one' }, { two: 'two' }]
);
assert.hasAllDeepKeys(new Set([{ one: 'one' }]), { one: 'one' });
assert.hasAllDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ one: 'one' },
{ two: 'two' },
]);
});containsAllDeepKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object contém todas as keys fornecidas. Como Sets e Maps podem ter objetos como chaves, você pode usar esta asserção para realizar uma comparação profunda. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.containsAllDeepKeys', () => {
assert.containsAllDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[1, 2],
]),
{ one: 'one' }
);
assert.containsAllDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[{ two: 'two' }, 'valueTwo'],
]),
[{ one: 'one' }, { two: 'two' }]
);
assert.containsAllDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), {
one: 'one',
});
assert.containsAllDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ one: 'one' },
{ two: 'two' },
]);
});doesNotHaveAnyDeepKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object não possui nenhuma das keys fornecidas. Como Sets e Maps podem ter objetos como chaves, você pode usar esta asserção para realizar uma comparação profunda. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.doesNotHaveAnyDeepKeys', () => {
assert.doesNotHaveAnyDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[1, 2],
]),
{ thisDoesNot: 'exist' }
);
assert.doesNotHaveAnyDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[{ two: 'two' }, 'valueTwo'],
]),
[{ twenty: 'twenty' }, { fifty: 'fifty' }]
);
assert.doesNotHaveAnyDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), {
twenty: 'twenty',
});
assert.doesNotHaveAnyDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ twenty: 'twenty' },
{ fifty: 'fifty' },
]);
});doesNotHaveAllDeepKeys
- Tipo:
<T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void
Afirma que object não possui pelo menos uma das keys fornecidas. Como Sets e Maps podem ter objetos como chaves, você pode usar esta asserção para realizar uma comparação profunda. Você pode fornecer um objeto único em vez de um array de chaves, e as chaves desse objeto serão usadas como o conjunto esperado de chaves.
import { assert, test } from 'vitest';
test('assert.doesNotHaveAllDeepKeys', () => {
assert.doesNotHaveAllDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[1, 2],
]),
{ thisDoesNot: 'exist' }
);
assert.doesNotHaveAllDeepKeys(
new Map([
[{ one: 'one' }, 'valueOne'],
[{ two: 'two' }, 'valueTwo'],
]),
[{ twenty: 'twenty' }, { one: 'one' }]
);
assert.doesNotHaveAllDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), {
twenty: 'twenty',
});
assert.doesNotHaveAllDeepKeys(new Set([{ one: 'one' }, { two: 'two' }]), [
{ one: 'one' },
{ fifty: 'fifty' },
]);
});throws
- Tipo:
(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string) => void(fn: () => void, errorLike?: ErrorConstructor | Error | null, errMsgMatcher?: RegExp | string | null, message?: string) => void
- Alias:
throwThrow
Se errorLike for um construtor de Error, afirma que fn lançará um erro que é uma instância de errorLike. Se errorLike for uma instância de Error, afirma que o erro lançado é a mesma instância de errorLike. Se errMsgMatcher for fornecido, também afirma que o erro lançado terá uma mensagem que corresponde a errMsgMatcher.
import { assert, test } from 'vitest';
test('assert.throws', () => {
assert.throws(fn, 'Error thrown must have this msg'); // Deve ter esta mensagem
assert.throws(fn, /Error thrown must have a msg that matches this/); // Deve corresponder a este padrão
assert.throws(fn, ReferenceError);
assert.throws(fn, errorInstance);
assert.throws(
fn,
ReferenceError,
'Error thrown must be a ReferenceError and have this msg' // Deve ser um ReferenceError e ter esta mensagem
);
assert.throws(
fn,
errorInstance,
'Error thrown must be the same errorInstance and have this msg' // Deve ser a mesma errorInstance e ter esta mensagem
);
assert.throws(
fn,
ReferenceError,
/Error thrown must be a ReferenceError and match this/ // Deve ser um ReferenceError e corresponder a isto
);
assert.throws(
fn,
errorInstance,
/Error thrown must be the same errorInstance and match this/ // Deve ser a mesma errorInstance e corresponder a isto
);
});doesNotThrow
- Tipo:
(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string) => void - Tipo:
(fn: () => void, errorLike?: ErrorConstructor | Error | null, errMsgMatcher?: RegExp | string | null, message?: string) => void
Se errorLike for um construtor de Error, afirma que fn não lançará um erro que é uma instância de errorLike. Se errorLike for uma instância de Error, afirma que o erro lançado não é a mesma instância de errorLike. Se errMsgMatcher for fornecido, também afirma que o erro lançado não terá uma mensagem que corresponde a errMsgMatcher.
import { assert, test } from 'vitest';
test('assert.doesNotThrow', () => {
assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); // Não deve ter esta mensagem
assert.doesNotThrow(fn, /Any Error thrown must not match this/); // Não deve corresponder a isto
assert.doesNotThrow(fn, Error);
assert.doesNotThrow(fn, errorInstance);
assert.doesNotThrow(fn, Error, 'Error must not have this message'); // Não deve ter esta mensagem
assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); // Não deve ter esta mensagem
assert.doesNotThrow(fn, Error, /Error must not match this/); // Não deve corresponder a isto
assert.doesNotThrow(fn, errorInstance, /Error must not match this/); // Não deve corresponder a isto
});operator
- Tipo:
(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string) => void
Compara val1 e val2 usando o operator.
import { assert, test } from 'vitest';
test('assert.operator', () => {
assert.operator(1, '<', 2, 'everything is ok'); // Tudo está correto
});closeTo
- Tipo:
(actual: number, expected: number, delta: number, message?: string) => void - Alias:
approximately
Afirma que actual é igual a expected, dentro de uma tolerância de +/- delta.
import { assert, test } from 'vitest';
test('assert.closeTo', () => {
assert.closeTo(1.5, 1, 0.5, 'numbers are close'); // Os números estão próximos
});sameMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 possuem os mesmos membros, independentemente da ordem. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.sameMembers', () => {
assert.sameMembers([1, 2, 3], [2, 1, 3], 'same members'); // Mesmos membros
});notSameMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 não possuem os mesmos membros, independentemente da ordem. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.notSameMembers', () => {
assert.notSameMembers([1, 2, 3], [5, 1, 3], 'not same members'); // Não são os mesmos membros
});sameDeepMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 possuem os mesmos membros, independentemente da ordem. Utiliza uma verificação de igualdade profunda.
import { assert, test } from 'vitest';
test('assert.sameDeepMembers', () => {
assert.sameDeepMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { a: 1 }, { c: 3 }],
'same deep members' // Mesmos membros (comparação profunda)
);
});notSameDeepMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 não possuem os mesmos membros, independentemente da ordem. Utiliza uma verificação de igualdade profunda.
import { assert, test } from 'vitest';
test('assert.notSameDeepMembers', () => {
assert.notSameDeepMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { a: 1 }, { c: 3 }],
'same deep members' // Mesmos membros (comparação profunda)
);
});sameOrderedMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 possuem os mesmos membros na mesma ordem. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.sameOrderedMembers', () => {
assert.sameOrderedMembers([1, 2, 3], [1, 2, 3], 'same ordered members'); // Mesmos membros na mesma ordem
});notSameOrderedMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 não possuem os mesmos membros na mesma ordem. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.notSameOrderedMembers', () => {
assert.notSameOrderedMembers(
[1, 2, 3],
[2, 1, 3],
'not same ordered members' // Não são os mesmos membros na mesma ordem
);
});sameDeepOrderedMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 possuem os mesmos membros na mesma ordem. Utiliza uma verificação de igualdade profunda.
import { assert, test } from 'vitest';
test('assert.sameDeepOrderedMembers', () => {
assert.sameDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ a: 1 }, { b: 2 }, { c: 3 }],
'same deep ordered members' // Mesmos membros na mesma ordem (comparação profunda)
);
});notSameDeepOrderedMembers
- Tipo:
<T>(set1: T[], set2: T[], message?: string) => void
Afirma que set1 e set2 não possuem os mesmos elementos na mesma ordem. Utiliza uma verificação de igualdade profunda (deep equality check).
import { assert, test } from 'vitest';
test('assert.notSameDeepOrderedMembers', () => {
assert.notSameDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ a: 1 }, { b: 2 }, { z: 5 }],
'não possuem os mesmos elementos na mesma ordem'
);
assert.notSameDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { a: 1 }, { c: 3 }],
'não possuem os mesmos elementos na mesma ordem'
);
});includeMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset está incluído em superset, independentemente da ordem. Utiliza uma verificação de igualdade estrita (===). Elementos duplicados são ignorados.
import { assert, test } from 'vitest';
test('assert.includeMembers', () => {
assert.includeMembers([1, 2, 3], [2, 1, 2], 'inclui os elementos');
});notIncludeMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset não está incluído em superset, independentemente da ordem. Utiliza uma verificação de igualdade estrita (===). Elementos duplicados são ignorados.
import { assert, test } from 'vitest';
test('assert.notIncludeMembers', () => {
assert.notIncludeMembers([1, 2, 3], [5, 1], 'não inclui os elementos');
});includeDeepMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset está incluído em superset, independentemente da ordem. Utiliza uma verificação de igualdade profunda (deep equality check). Elementos duplicados são ignorados.
import { assert, test } from 'vitest';
test('assert.includeDeepMembers', () => {
assert.includeDeepMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { a: 1 }, { b: 2 }],
'inclui os elementos (deep)'
);
});notIncludeDeepMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset não está incluído em superset, independentemente da ordem. Utiliza uma verificação de igualdade profunda (deep equality check). Elementos duplicados são ignorados.
import { assert, test } from 'vitest';
test('assert.notIncludeDeepMembers', () => {
assert.notIncludeDeepMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { f: 5 }],
'não inclui os elementos (deep)'
);
});includeOrderedMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset está incluído em superset na mesma ordem, começando pelo primeiro elemento de superset. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.includeOrderedMembers', () => {
assert.includeOrderedMembers(
[1, 2, 3],
[1, 2],
'inclui os elementos na ordem'
);
});notIncludeOrderedMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset não está incluído em superset na mesma ordem, começando pelo primeiro elemento de superset. Utiliza uma verificação de igualdade estrita (===).
import { assert, test } from 'vitest';
test('assert.notIncludeOrderedMembers', () => {
assert.notIncludeOrderedMembers(
[1, 2, 3],
[2, 1],
'não inclui os elementos na ordem'
);
assert.notIncludeOrderedMembers(
[1, 2, 3],
[2, 3],
'não inclui os elementos na ordem'
);
});includeDeepOrderedMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset está incluído em superset na mesma ordem, começando pelo primeiro elemento de superset. Utiliza uma verificação de igualdade profunda (deep equality check).
import { assert, test } from 'vitest';
test('assert.includeDeepOrderedMembers', () => {
assert.includeDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ a: 1 }, { b: 2 }],
'inclui os elementos na ordem (deep)'
);
});notIncludeDeepOrderedMembers
- Tipo:
<T>(superset: T[], subset: T[], message?: string) => void
Afirma que subset não está incluído em superset na mesma ordem, começando pelo primeiro elemento de superset. Utiliza uma verificação de igualdade profunda (deep equality check).
import { assert, test } from 'vitest';
test('assert.includeDeepOrderedMembers', () => {
assert.notIncludeDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ a: 1 }, { f: 5 }],
'não inclui os elementos na ordem (deep)'
);
assert.notIncludeDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { a: 1 }],
'não inclui os elementos na ordem (deep)'
);
assert.notIncludeDeepOrderedMembers(
[{ a: 1 }, { b: 2 }, { c: 3 }],
[{ b: 2 }, { c: 3 }],
'não inclui os elementos na ordem (deep)'
);
});oneOf
- Tipo:
<T>(inList: T, list: T[], message?: string) => void
Afirma que o valor inList (que não seja um objeto ou array) está presente no array list.
import { assert, test } from 'vitest';
test('assert.oneOf', () => {
assert.oneOf(1, [2, 1], 'Não encontrado na lista');
});changes
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier modifica a propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.changes', () => {
const obj = { val: 10 };
function fn() {
obj.val = 22;
}
assert.changes(fn, obj, 'val');
});changesBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a função modifier modifica a propriedade property do objeto object em um valor específico change.
import { assert, test } from 'vitest';
test('assert.changesBy', () => {
const obj = { val: 10 };
function fn() {
obj.val += 2;
}
assert.changesBy(fn, obj, 'val', 2);
});doesNotChange
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier não modifica a propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.doesNotChange', () => {
const obj = { val: 10 };
function fn() {
obj.val += 2;
}
assert.doesNotChange(fn, obj, 'val', 2);
});changesButNotBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change:number, message?: string) => void
Afirma que a função modifier modifica a propriedade property do objeto object, mas não pelo valor específico change.
import { assert, test } from 'vitest';
test('assert.changesButNotBy', () => {
const obj = { val: 10 };
function fn() {
obj.val += 10;
}
assert.changesButNotBy(fn, obj, 'val', 5);
});increases
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier aumenta o valor numérico da propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.increases', () => {
const obj = { val: 10 };
function fn() {
obj.val = 13;
}
assert.increases(fn, obj, 'val');
});increasesBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a função modifier aumenta o valor numérico da propriedade property do objeto object em um valor específico change.
import { assert, test } from 'vitest';
test('assert.increases', () => {
const obj = { val: 10 };
function fn() {
obj.val += 10;
}
assert.increasesBy(fn, obj, 'val', 10);
});doesNotIncrease
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier não aumenta o valor numérico da propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.doesNotIncrease', () => {
const obj = { val: 10 };
function fn() {
obj.val = 8;
}
assert.doesNotIncrease(fn, obj, 'val');
});increasesButNotBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a função modifier aumenta o valor numérico da propriedade property do objeto object, mas não pelo valor específico change.
import { assert, test } from 'vitest';
test('assert.increasesButNotBy', () => {
const obj = { val: 10 };
function fn() {
obj.val += 15;
}
assert.increasesButNotBy(fn, obj, 'val', 10);
});decreases
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier diminui o valor numérico da propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.decreases', () => {
const obj = { val: 10 };
function fn() {
obj.val = 5;
}
assert.decreases(fn, obj, 'val');
});decreasesBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a função modifier diminui o valor numérico da propriedade property do objeto object em um valor específico change.
import { assert, test } from 'vitest';
test('assert.decreasesBy', () => {
const obj = { val: 10 };
function fn() {
obj.val -= 5;
}
assert.decreasesBy(fn, obj, 'val', 5);
});doesNotDecrease
- Tipo:
<T>(modifier: Function, object: T, property: string, message?: string) => void
Afirma que a função modifier não diminui o valor numérico da propriedade property do objeto object.
import { assert, test } from 'vitest';
test('assert.doesNotDecrease', () => {
const obj = { val: 10 };
function fn() {
obj.val = 15;
}
assert.doesNotDecrease(fn, obj, 'val');
});doesNotDecreaseBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a execução de um modifier não diminui o valor da property numérica de um object, ou o valor de retorno do próprio modifier, em uma quantidade igual a change.
import { assert, test } from 'vitest';
test('assert.doesNotDecreaseBy', () => {
const obj = { val: 10 };
function fn() {
obj.val = 5;
}
assert.doesNotDecreaseBy(fn, obj, 'val', 1);
});decreasesButNotBy
- Tipo:
<T>(modifier: Function, object: T, property: string, change: number, message?: string) => void
Afirma que a execução de um modifier diminui o valor da property numérica de um object, ou o valor de retorno do próprio modifier, mas não em uma quantidade igual a change.
import { assert, test } from 'vitest';
test('assert.decreasesButNotBy', () => {
const obj = { val: 10 };
function fn() {
obj.val = 5;
}
assert.decreasesButNotBy(fn, obj, 'val', 1);
});ifError
- Tipo:
<T>(object: T, message?: string) => void
Verifica se object é um valor truthy (verdadeiro) e lança um erro se for. Isso é adicionado para permitir que o chai seja uma substituição direta para a classe assert do Node.js.
import { assert, test } from 'vitest';
test('assert.ifError', () => {
const err = new Error('I am a custom error');
assert.ifError(err); // Lança err novamente!
});isExtensible
- Tipo:
<T>(object: T, message?: string) => void - Alias:
extensible
Afirma que object é extensível (novas propriedades podem ser adicionadas a ele).
import { assert, test } from 'vitest';
test('assert.isExtensible', () => {
assert.isExtensible({});
});isNotExtensible
- Tipo:
<T>(object: T, message?: string) => void - Alias:
notExtensible
Afirma que object não é extensível (novas propriedades não podem ser adicionadas a ele).
import { assert, test } from 'vitest';
test('assert.isNotExtensible', () => {
const nonExtensibleObject = Object.preventExtensions({});
const sealedObject = Object.seal({});
const frozenObject = Object.freeze({});
assert.isNotExtensible(nonExtensibleObject);
assert.isNotExtensible(sealedObject);
assert.isNotExtensible(frozenObject);
});isSealed
- Tipo:
<T>(object: T, message?: string) => void - Alias:
sealed
Afirma que object está selado (novas propriedades não podem ser adicionadas a ele e suas propriedades existentes não podem ser removidas).
import { assert, test } from 'vitest';
test('assert.isSealed', () => {
const sealedObject = Object.seal({});
const frozenObject = Object.seal({});
assert.isSealed(sealedObject);
assert.isSealed(frozenObject);
});isNotSealed
- Tipo:
<T>(object: T, message?: string) => void - Alias:
notSealed
Afirma que object não está selado (novas propriedades podem ser adicionadas a ele e suas propriedades existentes podem ser removidas).
import { assert, test } from 'vitest';
test('assert.isNotSealed', () => {
assert.isNotSealed({});
});isFrozen
- Tipo:
<T>(object: T, message?: string) => void - Alias:
frozen
Afirma que object está congelado (novas propriedades não podem ser adicionadas a ele e suas propriedades existentes não podem ser modificadas).
import { assert, test } from 'vitest';
test('assert.isFrozen', () => {
const frozenObject = Object.freeze({});
assert.frozen(frozenObject);
});isNotFrozen
- Tipo:
<T>(object: T, message?: string) => void - Alias:
notFrozen
Afirma que object não está congelado (novas propriedades podem ser adicionadas a ele e suas propriedades existentes podem ser modificadas).
import { assert, test } from 'vitest';
test('assert.isNotFrozen', () => {
assert.isNotFrozen({});
});isEmpty
- Tipo:
<T>(target: T, message?: string) => void - Alias:
empty
Afirma que o target está vazio. Para arrays e strings, verifica a propriedade length. Para instâncias de Map e Set, verifica a propriedade size. Para objetos (que não são funções), obtém o número de chaves string enumeráveis.
import { assert, test } from 'vitest';
test('assert.isEmpty', () => {
assert.isEmpty([]);
assert.isEmpty('');
assert.isEmpty(new Map());
assert.isEmpty({});
});isNotEmpty
- Tipo:
<T>(object: T, message?: string) => void - Alias:
notEmpty
Afirma que o target não está vazio (contém valores). Para arrays e strings, verifica a propriedade length. Para instâncias de Map e Set, verifica a propriedade size. Para objetos (que não são funções), obtém o número de chaves string enumeráveis.
import { assert, test } from 'vitest';
test('assert.isNotEmpty', () => {
assert.isNotEmpty([1, 2]);
assert.isNotEmpty('34');
assert.isNotEmpty(new Set([5, 6]));
assert.isNotEmpty({ key: 7 });
});