# Testare l'applicazione con il test runner integrato

> Scrivi un test.js che avvia l'app, registra i test con Test.push(), controlla i risultati con Test.print() ed esce con un codice diverso da zero quando uno fallisce.

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

Total.js ha un piccolo test runner, `total5/test`. Un file di test è un normale script Total.js: carica il framework e il runner, avvia l'applicazione e, quando è `ready`, registra i suoi test. `Test.push(name, fn)` aggiunge un test; `fn(next)` fa il suo lavoro e chiama `next()` per proseguire con il successivo. `Test.print(message, error)` segnala un controllo: passa `null` come `error` per il successo (viene stampato `[OK]`) o un messaggio per il fallimento (viene stampato `[FAIL]` e il processo termina con codice 1). `Test.run()` esegue i test registrati in ordine e termina con codice 0 alla fine.

Poiché un fallimento termina il processo con un codice diverso da zero, il file può essere chiamato da `npm test` e da qualsiasi servizio di CI. Aspetta un momento (circa 500 ms) dopo `ready` prima della prima richiesta: una richiesta inviata subito può ancora ricevere un 404. Usa `RESTBuilder` (o `REQUEST`) contro il server locale per testare le rotte e chiama le azioni direttamente 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();
}
```
