---
title: Tests unitarios
project: Total.js V5
version: 0.0.20
section: reference
language: es
license: MIT
url: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/unit-tests/
updated: 2026-11-18T16:57:34.578Z
---

# Tests unitarios

> El ejecutor Test de total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count y Test.items.

El ejecutor `Test` de `total5/test`. La guía [Tests unitarios](../../guides/unit-tests/) explica cómo usarlo, con ejemplos.

## API

### Test

Type: `class`

El ejecutor de tests global creado por `require('total5/test')`.

Returns: `Object`

Carga `total5` cuando no está cargado y crea el objeto global `Test` con `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` e `items`. Ejecuta el archivo de tests con `node`, o los scripts de test de un proyecto con `total5 test` (consulta [Línea de comandos](../../reference/command-line/)).

Example: Cargar
```js
require('total5/test');

Test.push('Numbers', function(next) {
	Test.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');
	next();
});

Test.run();
```

### Test.push(name, fn)

Type: `method`

Añade un grupo de tests.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | El nombre que se imprime como cabecera del grupo. |
| `fn` | `Function` | yes |  | `function(next)` |

Returns: `undefined`

Los grupos se ejecutan en el orden en que se añadieron. `fn` recibe `next` y debe llamarlo cuando el grupo termina, también después de comprobaciones asíncronas.

Example: Grupo asíncrono
```js
Test.push('Download', function(next) {
	RESTBuilder.GET('https://www.example.com').callback(function(err) {
		Test.print('GET', err);
		next();
	});
});
```

### Test.run([callback])

Type: `method`

Ejecuta todos los grupos uno tras otro.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function()` que se llama en lugar de terminar el proceso. |

Returns: `undefined`

Imprime la cabecera de cada grupo y luego el número de comprobaciones y el tiempo. Sin `callback`, el proceso termina con el código de salida 0 cuando todos los grupos han terminado.

Example: Ejecutar y detener el servidor
```js
Test.run(function() {
	F.exit();
});
```

### Test.print(message, [err])

Type: `method`

Imprime el resultado de una comprobación.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | El nombre de la comprobación. |
| `err` | `Error|String` | no |  | El motivo de un fallo. |

Returns: `undefined`

Sin `err` (o con un valor falso) imprime `[OK] message` y cuenta la comprobación. Con `err` imprime `[FAIL] message`, lanza el error (una cadena se convierte en un `Error`) y termina el proceso con el código de salida 1.

Example: Comprobar un valor
```js
var value = 'Total.js'.slug();
Test.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);
```

### Test.start(message)

Type: `method`

Imprime una cabecera entre dos líneas divisorias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | El texto de la cabecera. |

Returns: `undefined`

`Test.run()` la llama con el nombre de cada grupo. Llámala tú mismo para separar partes de un grupo largo.

Example: Cabecera
```js
Test.start('Second part');
```

### Test.fake(name, action)

Type: `method`

Sustituye una acción por una falsa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | El nombre de la acción. |
| `action` | `Object` | yes |  | La definición de la falsa, el mismo objeto que en `NEWACTION()`. |

Returns: `Object` La acción falsa registrada.

Guarda aparte la acción `name` (solo la primera vez hasta `Test.restore()`) y registra `action` con el mismo nombre mediante `NEWACTION()`. Las llamadas a `ACTION(name)` ejecutan entonces la falsa. También funciona con un nombre que no tiene acción.

Example: Falsear y restaurar
```js
NEWACTION('Users/read', {
	action: $ => $.callback('real')
});

Test.push('Fake', async function(next) {
	Test.fake('Users/read', { action: $ => $.callback('fake') });
	var value = await ACTION('Users/read').promise();
	Test.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);
	Test.restore();
	value = await ACTION('Users/read').promise();
	Test.print('restore', value === 'real' ? null : 'Unexpected: ' + value);
	next();
});

Test.run();
```

### Test.count

Type: `property`

El número de comprobaciones impresas por `Test.print()`.

Returns: `Number`

`Test.run()` lo imprime al final como `Tests: <count>`.

Example: Leer
```js
Test.run(function() {
	console.log('Checks:', Test.count);
	process.exit(0);
});
```

### Test.restore()

Type: `method`

Vuelve a poner las acciones originales.

Returns: `undefined`

Elimina todas las falsas registradas con `Test.fake()` y vuelve a poner las acciones originales. Una falsa de un nombre que no tenía acción solo se elimina.

Example: Después de un grupo
```js
Test.push('Payments', function(next) {
	Test.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });
	// ... the checks
	Test.restore();
	next();
});
```

### Test.items

Type: `property`

Los grupos añadidos con `Test.push()`.

Returns: `Array`

Un array de objetos `{ name, fn }`. `Test.run()` los ejecuta uno a uno; el array los conserva.

Example: Contar grupos
```js
console.log(Test.items.length, 'groups');
```
