# Prueba la aplicación con el ejecutor de tests integrado

> Escribe un test.js que arranque la aplicación, registre tests con Test.push(), compruebe los resultados con Test.print() y termine con un código distinto de cero cuando uno falle.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: es
Content-SHA256: 8d7f209cd439d84796261acd08f2d616bb6804056706818898ed3065403f3abd
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

Total.js incluye un pequeño ejecutor de tests, `total5/test`. Un archivo de test es un script normal de Total.js: carga el framework y el ejecutor, arranca la aplicación y, cuando está `ready`, registra sus tests. `Test.push(name, fn)` añade un test; `fn(next)` hace su trabajo y llama a `next()` para continuar con el siguiente. `Test.print(message, error)` informa de una comprobación: pasa `null` como `error` si fue bien (se imprime `[OK]`) o un mensaje si falló (se imprime `[FAIL]` y el proceso termina con código 1). `Test.run()` ejecuta los tests registrados en orden y termina con código 0 al final.

Como un fallo termina el proceso con un código distinto de cero, el archivo puede llamarse desde `npm test` y desde cualquier servicio de CI. Espera un momento (unos 500 ms) tras `ready` antes de la primera petición: una petición enviada de inmediato todavía puede recibir un 404. Usa `RESTBuilder` (o `REQUEST`) contra el servidor local para probar rutas, y llama a las acciones directamente con `ACTION()`.

```js controllers/sum.js
exports.install = function() {
	ROUTE('GET /sum/{a}/{b}/', sum);
	ROUTE('GET /dir/', dir);
};

function sum($) {
	$.json({ total: +$.params.a + +$.params.b });
}

function dir($) {
	$.json({ dir: PATH.root() });
}
```

```js test.js
require('total5');
require('total5/test');

// Another port than the application uses, so both can run
Total.run({ port: 8765, release: false, watcher: false });

ON('ready', function() {

	// A request sent in the same tick as "ready" can still get a 404, so give the routes a moment
	setTimeout(runtests, 500);
});

function runtests() {

	Test.push('The sum route', function(next) {
		RESTBuilder.GET('http://127.0.0.1:8765/sum/2/3/').exec(function(err, response) {
			Test.print('2 + 3 = 5', response && response.total === 5 ? null : 'Expected 5, got ' + JSON.stringify(response));
			next();
		});
	});

	Test.push('Unknown route', function(next) {
		RESTBuilder.GET('http://127.0.0.1:8765/missing/').exec(function(err, response, output) {
			Test.print('/missing/ answers 404', output.status === 404 ? null : 'Expected 404, got ' + output.status);
			next();
		});
	});

	Test.run();
}
```
