ForgeTotal.js 5
it

Total.js 5

Testare l'applicazione con il test runner integrato

Total.js 5 · total5@0.0.19 testingci Eseguita con Total.js 5

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().

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() });
}
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();
}