Skip to content
Vitest 3
Main Navigation Guia & APIConfiguraçãoModo NavegadorAPI Avançada
3.2.0
2.1.9
1.6.1
0.34.6

Português – Brasil

English
简体中文
繁體中文
Español
Français
Русский
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

Português – Brasil

English
简体中文
繁體中文
Español
Français
Русский
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

Aparência

Sidebar Navigation

Introdução

Por que Vitest

Primeiros Passos

Recursos

Configurando o Vitest

API

Referência da API de Teste

Funções Mock

Vi

expect

expectTypeOf

assert

assertType

Guia

Interface de Linha de Comando

Filtragem de Testes

Projetos de Teste

Reporters

Cobertura

Snapshot

Mocking

Paralelismo

Testando Tipos

Vitest UI

Testes no Código-Fonte

Contexto de Testes

Anotações em Testes

Ambiente de Teste

Estendendo Matchers

Integrações com IDEs

Depuração

Erros Comuns

Guia de Migração

Migrando para o Vitest 3.0

Migrando do Jest

Desempenho

Análise de Desempenho de Testes

Melhorando o Desempenho

Modo Navegador

APIs Avançadas

Comparações com Outros Test Runners

Nesta página

assert ​

O Vitest reexporta o método assert do chai para verificar invariantes.

assert ​

  • Tipo: (expression: any, message?: string) => asserts expression

Afirma que a expression fornecida é verdadeira; caso contrário, a asserção falha.

ts
import { assert, test } from 'vitest';

test('assert', () => {
  assert('foo' !== 'bar', 'foo não deve ser igual a bar');
});

fail ​

  • Tipo:
    • (message?: string) => never
    • <T>(actual: T, expected: T, message?: string, operator?: string) => never

Força uma falha de asserção.

ts
import { assert, test } from 'vitest';

test('assert.fail', () => {
  assert.fail('mensagem de erro na falha');
  assert.fail('foo', 'bar', 'foo não é bar', '===');
});

isOk ​

  • Tipo: <T>(value: T, message?: string) => void
  • Apelido: ok

Afirma que o value fornecido é verdadeiro (truthy).

ts
import { assert, test } from 'vitest';

test('assert.isOk', () => {
  assert.isOk('foo', 'qualquer valor truthy é ok');
  assert.isOk(false, 'isso falhará, pois false não é truthy');
});

isNotOk ​

  • Tipo: <T>(value: T, message?: string) => void
  • Apelido: notOk

Afirma que o value fornecido é falso (falsy).

ts
import { assert, test } from 'vitest';

test('assert.isNotOk', () => {
  assert.isNotOk('foo', 'isso falhará, pois qualquer valor truthy é considerado ok');
  assert.isNotOk(false, 'isso passará, pois false é falsy');
});

equal ​

  • Tipo: <T>(actual: T, expected: T, message?: string) => void

Afirma a igualdade não estrita (==) de actual e expected.

ts
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 (!=) de actual e expected.

ts
import { assert, test } from 'vitest';

test('assert.notEqual', () => {
  assert.notEqual(Math.sqrt(4), 3);
});

strictEqual ​

  • Tipo: <T>(actual: T, expected: T, message?: string) => void

Afirma a igualdade estrita (===) de actual e expected.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
import { assert, test } from 'vitest';

const error = { message: 'ocorreu um erro' };

test('assert.isNotNull', () => {
  assert.isNotNull(error, 'error não é nulo, mas um objeto');
});

isNaN ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é NaN.

ts
import { assert, test } from 'vitest';

const calculation = 1 * 'vitest';

test('assert.isNaN', () => {
  assert.isNaN(calculation, '1 * "vitest" é NaN');
});

isNotNaN ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value não é NaN.

ts
import { assert, test } from 'vitest';

const calculation = 1 * 2;

test('assert.isNotNaN', () => {
  assert.isNotNaN(calculation, '1 * 2 não é NaN, mas 2');
});

exists ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value não é null nem undefined.

ts
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.

ts
import { assert, test } from 'vitest';

const foo = null;
const bar = undefined;

test('assert.notExists', () => {
  assert.notExists(foo, 'foo é nulo, então não existe');
  assert.notExists(bar, 'bar é undefined, então não existe');
});

isUndefined ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é undefined.

ts
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.

ts
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
  • Apelido: isCallable Afirma que value é uma função.
ts
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
  • Apelido: isNotCallable

Afirma que value não é uma função.

ts
import { assert, test } from 'vitest';

const name = 'foo';

test('assert.isNotFunction', () => {
  assert.isNotFunction(name, 'name não é uma função, mas 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 de subclasse.

ts
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 (conforme revelado por Object.prototype.toString). A asserção não corresponde a objetos de subclasse.

ts
import { assert, test } from 'vitest';

const someThing = 'redCircle';

test('assert.isNotObject', () => {
  assert.isNotObject(someThing, 'someThing não é um objeto, mas sim uma string');
});

isArray ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é um array.

ts
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.

ts
import { assert, test } from 'vitest';

const color = 'red';

test('assert.isNotArray', () => {
  assert.isNotArray(color, 'color não é um array, mas uma string');
});

isString ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é uma string.

ts
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.

ts
import { assert, test } from 'vitest';

const color = ['red', 'green', 'yellow'];

test('assert.isNotString', () => {
  assert.isNotString(color, 'color não é uma string, mas um array');
});

isNumber ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é um número.

ts
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.

ts
import { assert, test } from 'vitest';

const colors = '3 colors';

test('assert.isNotNumber', () => {
  assert.isNotNumber(colors, 'colors não é um número, mas uma string');
});

isFinite ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é um número finito (não NaN, Infinity).

ts
import { assert, test } from 'vitest';

const colors = 3;

test('assert.isFinite', () => {
  assert.isFinite(colors, 'colors é um número, não NaN ou Infinity');
});

isBoolean ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value é um booleano.

ts
import { assert, test } from 'vitest';

const isReady = true;

test('assert.isBoolean', () => {
  assert.isBoolean(isReady, 'isReady é um booleano');
});

isNotBoolean ​

  • Tipo: <T>(value: T, message?: string) => void

Afirma que value não é um booleano.

ts
import { assert, test } from 'vitest';

const isReady = 'sure';

test('assert.isNotBoolean', () => {
  assert.isNotBoolean(isReady, 'isReady não é um booleano, mas 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.

ts
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 um nulo');
  assert.typeOf(undefined, 'undefined', 'temos um indefinido');
});

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.

ts
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.

ts
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.

ts
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.notInstanceOf', () => {
  assert.notInstanceOf(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 afirmar a inclusão de um valor em um array, uma substring em uma string ou um subconjunto de propriedades em um objeto.

ts
import { assert, test } from 'vitest';

test('assert.include', () => {
  assert.include([1, 2, 3], 2, 'array contém valor');
  assert.include('foobar', 'foo', 'string contém substring');
  assert.include(
    { foo: 'bar', hello: 'universe' },
    { foo: 'bar' },
    'objeto contém 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 afirmar a ausência de um valor em um array, uma substring em uma string ou um subconjunto de propriedades em um objeto.

ts
import { assert, test } from 'vitest';

test('assert.notInclude', () => {
  assert.notInclude([1, 2, 3], 4, "array não contém 4");
  assert.notInclude('foobar', 'baz', "foobar não contém baz");
  assert.notInclude(
    { foo: 'bar', hello: 'universe' },
    { foo: 'baz' },
    "objeto não contém 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 afirmar a inclusão de um valor em um array ou um subconjunto de propriedades em um objeto. É usada a igualdade profunda.

ts
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 afirmar a ausência de um valor em um array ou um subconjunto de propriedades em um objeto. É usada a igualdade profunda.

ts
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 afirmar a inclusão de um subconjunto de propriedades em um objeto. Permite o uso de notação de ponto e colchetes para referenciar propriedades aninhadas. Caracteres como [ e . em nomes de propriedades podem ser escapados usando barras invertidas duplas.

ts
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 afirmar a inclusão de um subconjunto de propriedades em um objeto. Permite o uso de notação de ponto e colchetes para referenciar propriedades aninhadas. Caracteres como [ e . em nomes de propriedades podem ser escapados usando barras invertidas duplas.

ts
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 afirmar a inclusão de um subconjunto de propriedades em um objeto, verificando a igualdade profunda. Permite o uso de notação de ponto e colchetes para referenciar propriedades aninhadas. Caracteres como [ e . em nomes de propriedades podem ser escapados usando barras invertidas duplas.

ts
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 afirmar a ausência de um subconjunto de propriedades em um objeto, verificando a igualdade profunda. Permite o uso de notação de ponto e colchetes para referenciar propriedades aninhadas. Caracteres como [ e . em nomes de propriedades podem ser escapados usando barras invertidas duplas.

ts
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 afirmar a inclusão de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas.

ts
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 afirmar a ausência de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas.

ts
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

Afirma que haystack inclui needle. Pode ser usado para afirmar a inclusão de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas e verificando a igualdade profunda.

ts
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

Afirma que haystack não inclui needle. Pode ser usado para afirmar a ausência de um subconjunto de propriedades em um objeto, ignorando propriedades herdadas e verificando a igualdade profunda.

ts
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

Afirma que value corresponde à expressão regular regexp.

ts
import { assert, test } from 'vitest';

test('assert.match', () => {
  assert.match('foobar', /^foo/, 'expressão regular corresponde');
});

notMatch ​

  • Tipo: (value: string, regexp: RegExp, message?: string) => void

Afirma que value não corresponde à expressão regular regexp.

ts
import { assert, test } from 'vitest';

test('assert.notMatch', () => {
  assert.notMatch('foobar', /^foo/, 'expressão regular não corresponde');
});

property ​

  • Tipo: <T>(object: T, property: string, message?: string) => void

Afirma que object tem uma propriedade direta ou herdada nomeada por property.

ts
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

Afirma que object não tem uma propriedade direta ou herdada nomeada por property.

ts
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

Afirma que object tem uma propriedade direta ou herdada nomeada por property com um valor dado por value. Usa uma verificação de igualdade estrita (===).

ts
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

Afirma que object não tem uma propriedade direta ou herdada nomeada por property com um valor dado por value. Usa uma verificação de igualdade estrita (===).

ts
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

Afirma que object tem uma propriedade direta ou herdada nomeada por property com um valor dado por value. Usa uma verificação de igualdade profunda.

ts
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

Afirma que object não tem uma propriedade direta ou herdada nomeada por property com um valor dado por value. Usa uma verificação de igualdade profunda.

ts
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

Afirma que object tem uma propriedade direta ou herdada nomeada por property, que pode ser uma string usando notação de ponto e colchetes para referência aninhada.

ts
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

Afirma que object não tem uma propriedade direta ou herdada nomeada por property, que pode ser uma string usando notação de ponto e colchetes para referência aninhada.

ts
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

Afirma que object tem uma propriedade nomeada por property com valor dado por value. property pode usar notação de ponto e colchetes para referência aninhada. Usa uma verificação de igualdade estrita (===).

ts
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

Afirma que object não tem uma propriedade nomeada por property com valor dado por value. property pode usar notação de ponto e colchetes para referência aninhada. Usa uma verificação de igualdade estrita (===).

ts
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

Afirma que object tem uma propriedade nomeada por property com um valor dado por value. property pode usar notação de ponto e colchetes para referência aninhada. Usa uma verificação de igualdade profunda.

ts
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

Afirma que object não tem uma propriedade nomeada por property com valor dado por value. property pode usar notação de ponto e colchetes para referência aninhada. Usa uma verificação de igualdade profunda.

ts
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

Afirma que object tem um length ou size com o valor esperado.

ts
import { assert, test } from 'vitest';

test('assert.lengthOf', () => {
  assert.lengthOf([1, 2, 3], 3, 'array tem comprimento de 3');
  assert.lengthOf('foobar', 6, 'string tem comprimento de 6');
  assert.lengthOf(new Set([1, 2, 3]), 3, 'set tem tamanho de 3');
  assert.lengthOf(
    new Map([
      ['a', 1],
      ['b', 2],
      ['c', 3],
    ]),
    3,
    'map tem tamanho de 3'
  );
});

hasAnyKeys ​

  • Tipo: <T>(object: T, keys: Array<Object | string> | { [key: string]: any }, message?: string) => void

Afirma que object tem pelo menos uma das keys fornecidas. Você também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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

Afirma que object tem todas e apenas todas as keys fornecidas. Você também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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

Afirma que object tem todas as keys fornecidas, mas pode ter mais chaves não listadas. Você também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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 tem nenhuma das keys fornecidas. Você também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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 tem pelo menos uma das keys fornecidas. Você também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
import { assert, test } from 'vitest';

test('assert.doesNotHaveAllKeys', () => {
  assert.doesNotHaveAllKeys({ foo: 1, bar: 2, baz: 3 }, [
    'one',
    'two',
    'example',
  ]);
  assert.doesNotHaveAllKeys(
    { foo: 1, bar: 2, baz: 3 },
    { one: 1, two: 2, example: 'foo' }
  );
  assert.doesNotHaveAllKeys(
    new Map([
      [{ foo: 1 }, 'bar'],
      ['key', 'value'],
    ]),
    [{ one: 'two' }, 'example']
  );
  assert.doesNotHaveAllKeys(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 tem 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ê também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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 tem todas e apenas 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ê também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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ê também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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 tem 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ê também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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 tem 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ê também pode fornecer um único objeto em vez de um array de chaves, e suas chaves serão usadas como o conjunto esperado de chaves.

ts
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
  • Apelido:
    • throw
    • Throw

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 que errorLike. Se errMsgMatcher for fornecido, também afirma que o erro lançado terá uma mensagem que corresponde a errMsgMatcher.

ts
import { assert, test } from 'vitest';

test('assert.throws', () => {
  assert.throws(fn, 'Error thrown must have this msg');
  assert.throws(fn, /Error thrown must have a msg that matches this/);
  assert.throws(fn, ReferenceError);
  assert.throws(fn, errorInstance);
  assert.throws(
    fn,
    ReferenceError,
    'Error thrown must be a ReferenceError and have this msg'
  );
  assert.throws(
    fn,
    errorInstance,
    'Error thrown must be the same errorInstance and have this msg'
  );
  assert.throws(
    fn,
    ReferenceError,
    /Error thrown must be a ReferenceError and match this/
  );
  assert.throws(
    fn,
    errorInstance,
    /Error thrown must be the same errorInstance and match this/
  );
});

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 que errorLike. Se errMsgMatcher for fornecido, também afirma que o erro lançado não terá uma mensagem que corresponda a errMsgMatcher.

ts
import { assert, test } from 'vitest';

test('assert.doesNotThrow', () => {
  assert.doesNotThrow(fn, 'Any Error thrown must not have this message');
  assert.doesNotThrow(fn, /Any Error thrown must not match this/);
  assert.doesNotThrow(fn, Error);
  assert.doesNotThrow(fn, errorInstance);
  assert.doesNotThrow(fn, Error, 'Error must not have this message');
  assert.doesNotThrow(fn, errorInstance, 'Error must not have this message');
  assert.doesNotThrow(fn, Error, /Error must not match this/);
  assert.doesNotThrow(fn, errorInstance, /Error must not match this/);
});

operator ​

  • Tipo: (val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string) => void

Compara val1 e val2 usando operator.

ts
import { assert, test } from 'vitest';

test('assert.operator', () => {
  assert.operator(1, '<', 2, 'tudo está ok');
});

closeTo ​

  • Tipo: (actual: number, expected: number, delta: number, message?: string) => void
  • Apelido: approximately

Afirma que o actual é igual a expected, dentro de um intervalo de +/- delta.

ts
import { assert, test } from 'vitest';

test('assert.closeTo', () => {
  assert.closeTo(1.5, 1, 0.5, 'números estão próximos');
});

sameMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 têm os mesmos membros em qualquer ordem. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.sameMembers', () => {
  assert.sameMembers([1, 2, 3], [2, 1, 3], 'mesmos membros');
});

notSameMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 não têm os mesmos membros em qualquer ordem. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.notSameMembers', () => {
  assert.notSameMembers([1, 2, 3], [5, 1, 3], 'não são os mesmos membros');
});

sameDeepMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 têm os mesmos membros em qualquer ordem. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.sameDeepMembers', () => {
  assert.sameDeepMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { a: 1 }, { c: 3 }],
    'mesmos membros profundos'
  );
});

notSameDeepMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 não têm os mesmos membros em qualquer ordem. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.notSameDeepMembers', () => {
  assert.notSameDeepMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { a: 1 }, { c: 3 }],
    'não são os mesmos membros profundos'
  );
});

sameOrderedMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 têm os mesmos membros na mesma ordem. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.sameOrderedMembers', () => {
  assert.sameOrderedMembers([1, 2, 3], [1, 2, 3], 'mesmos membros ordenados');
});

notSameOrderedMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 não têm os mesmos membros na mesma ordem. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.notSameOrderedMembers', () => {
  assert.notSameOrderedMembers(
    [1, 2, 3],
    [2, 1, 3],
    'não são os mesmos membros ordenados'
  );
});

sameDeepOrderedMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 têm os mesmos membros na mesma ordem. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.sameDeepOrderedMembers', () => {
  assert.sameDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    'mesmos membros ordenados profundos'
  );
});

notSameDeepOrderedMembers ​

  • Tipo: <T>(set1: T[], set2: T[], message?: string) => void

Afirma que set1 e set2 não têm os mesmos membros na mesma ordem. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.notSameDeepOrderedMembers', () => {
  assert.notSameDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ a: 1 }, { b: 2 }, { z: 5 }],
    'não são os mesmos membros ordenados profundos'
  );
  assert.notSameDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { a: 1 }, { c: 3 }],
    'não são os mesmos membros ordenados profundos'
  );
});

includeMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset está incluído em superset em qualquer ordem. Usa uma verificação de igualdade estrita (===). Duplicatas são ignoradas.

ts
import { assert, test } from 'vitest';

test('assert.includeMembers', () => {
  assert.includeMembers([1, 2, 3], [2, 1, 2], 'inclui membros');
});

notIncludeMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset não está incluído em superset em qualquer ordem. Usa uma verificação de igualdade estrita (===). Duplicatas são ignoradas.

ts
import { assert, test } from 'vitest';

test('assert.notIncludeMembers', () => {
  assert.notIncludeMembers([1, 2, 3], [5, 1], 'não inclui membros');
});

includeDeepMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset está incluído em superset em qualquer ordem. Usa uma verificação de igualdade profunda. Duplicatas são ignoradas.

ts
import { assert, test } from 'vitest';

test('assert.includeDeepMembers', () => {
  assert.includeDeepMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { a: 1 }, { b: 2 }],
    'inclui membros profundos'
  );
});

notIncludeDeepMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset não está incluído em superset em qualquer ordem. Usa uma verificação de igualdade profunda. Duplicatas são ignoradas.

ts
import { assert, test } from 'vitest';

test('assert.notIncludeDeepMembers', () => {
  assert.notIncludeDeepMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { f: 5 }],
    'não inclui membros profundos'
  );
});

includeOrderedMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset está incluído em superset na mesma ordem, começando com o primeiro elemento em superset. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.includeOrderedMembers', () => {
  assert.includeOrderedMembers([1, 2, 3], [1, 2], 'inclui membros ordenados');
});

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 com o primeiro elemento em superset. Usa uma verificação de igualdade estrita (===).

ts
import { assert, test } from 'vitest';

test('assert.notIncludeOrderedMembers', () => {
  assert.notIncludeOrderedMembers(
    [1, 2, 3],
    [2, 1],
    'não inclui membros ordenados'
  );
  assert.notIncludeOrderedMembers(
    [1, 2, 3],
    [2, 3],
    'não inclui membros ordenados'
  );
});

includeDeepOrderedMembers ​

  • Tipo: <T>(superset: T[], subset: T[], message?: string) => void

Afirma que subset está incluído em superset na mesma ordem, começando com o primeiro elemento em superset. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.includeDeepOrderedMembers', () => {
  assert.includeDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ a: 1 }, { b: 2 }],
    'inclui membros ordenados profundos'
  );
});

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 com o primeiro elemento em superset. Usa uma verificação de igualdade profunda.

ts
import { assert, test } from 'vitest';

test('assert.notIncludeDeepOrderedMembers', () => {
  assert.notIncludeDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ a: 1 }, { f: 5 }],
    'não inclui membros ordenados profundos'
  );
  assert.notIncludeDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { a: 1 }],
    'não inclui membros ordenados profundos'
  );
  assert.notIncludeDeepOrderedMembers(
    [{ a: 1 }, { b: 2 }, { c: 3 }],
    [{ b: 2 }, { c: 3 }],
    'não inclui membros ordenados profundos'
  );
});

oneOf ​

  • Tipo: <T>(inList: T, list: T[], message?: string) => void

Afirma que o valor inList (não objeto, não array) aparece no array plano list.

ts
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 um modifier altera a property de um object.

ts
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 um modifier altera a property de um object por um change.

ts
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 um modifier não altera a property de um object.

ts
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 um modifier altera a property de um object, mas não pela quantidade change especificada.

ts
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 um modifier aumenta a property numérica de um object.

ts
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 um modifier aumenta a property numérica de um object ou o valor de retorno de um modifier por um change.

ts
import { assert, test } from 'vitest';

test('assert.increasesBy', () => {
  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 um modifier não aumenta a property numérica de um object.

ts
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 um modifier aumenta a property numérica de um object ou o valor de retorno de um modifier, mas não pela quantidade change especificada.

ts
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 um modifier diminui a property numérica de um object.

ts
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 um modifier diminui a property numérica de um object ou o valor de retorno de um modifier por um change.

ts
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 um modifier não diminui a property numérica de um object.

ts
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 um modifier não diminui a property numérica de um object ou o valor de retorno de um modifier pela quantidade change especificada.

ts
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 um modifier diminui a property numérica de um object ou o valor de retorno de um modifier, mas não pela quantidade change especificada.

ts
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

Afirma se object não é um valor falso (falsy), e lança um erro se for um valor verdadeiro (truthy). Isso é adicionado para permitir que o Chai seja um substituto direto para a classe assert do Node.

ts
import { assert, test } from 'vitest';

test('assert.ifError', () => {
  const err = new Error('I am a custom error');
  assert.ifError(err); // Rethrows err!
});

isExtensible ​

  • Tipo: <T>(object: T, message?: string) => void
  • Apelido: extensible

Afirma que object é extensível (pode ter novas propriedades adicionadas a ele).

ts
import { assert, test } from 'vitest';

test('assert.isExtensible', () => {
  assert.isExtensible({});
});

isNotExtensible ​

  • Tipo: <T>(object: T, message?: string) => void
  • Apelido: notExtensible

Afirma que object não é extensível (não pode ter novas propriedades adicionadas a ele).

ts
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
  • Apelido: sealed

Afirma que object está selado (não pode ter novas propriedades adicionadas a ele e suas propriedades existentes não podem ser removidas).

ts
import { assert, test } from 'vitest';

test('assert.isSealed', () => {
  const sealedObject = Object.seal({});
  const frozenObject = Object.freeze({});

  assert.isSealed(sealedObject);
  assert.isSealed(frozenObject);
});

isNotSealed ​

  • Tipo: <T>(object: T, message?: string) => void
  • Apelido: notSealed

Afirma que object não está selado (pode ter novas propriedades adicionadas a ele ou suas propriedades existentes podem ser removidas).

ts
import { assert, test } from 'vitest';

test('assert.isNotSealed', () => {
  assert.isNotSealed({});
});

isFrozen ​

  • Tipo: <T>(object: T, message?: string) => void
  • Apelido: frozen

Afirma que o objeto está congelado (não pode ter novas propriedades adicionadas a ele e suas propriedades existentes não podem ser modificadas).

ts
import { assert, test } from 'vitest';

test('assert.isFrozen', () => {
  const frozenObject = Object.freeze({});
  assert.frozen(frozenObject);
});

isNotFrozen ​

  • Tipo: <T>(object: T, message?: string) => void
  • Apelido: notFrozen

Afirma que object não está congelado (pode ter novas propriedades adicionadas a ele ou suas propriedades existentes podem ser modificadas).

ts
import { assert, test } from 'vitest';

test('assert.isNotFrozen', () => {
  assert.isNotFrozen({});
});

isEmpty ​

  • Tipo: <T>(target: T, message?: string) => void
  • Apelido: empty

Afirma que o target não contém nenhum valor. Para arrays e strings, ele verifica a propriedade length. Para instâncias de Map e Set, ele verifica a propriedade size. Para objetos não-função, ele obtém a contagem de suas próprias chaves de string enumeráveis.

ts
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
  • Apelido: notEmpty

Afirma que o target contém valores. Para arrays e strings, ele verifica a propriedade length. Para instâncias de Map e Set, ele verifica a propriedade size. Para objetos não-função, ele obtém a contagem de suas próprias chaves de string enumeráveis.

ts
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 });
});
Pager
AnteriorexpectTypeOf
PróximoassertType

Distribuído sob a Licença MIT.

Copyright (c) 2021-Present Vitest Team

https://vitest.dev/api/assert

Distribuído sob a Licença MIT.

Copyright (c) 2021-Present Vitest Team