# Testa un componente Flow da solo con Flow.test()

> Carica un componente in un flusso a sé, inviagli un messaggio dal codice e leggi ciò che invia alle sue uscite, senza costruire l'intero flusso.

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

`Flow.test(name, source, [config], [init])` costruisce un flusso con **un** componente (il `source` è il suo codice, come nella ricetta di FlowStream, e `config` sostituisce la sua configurazione) e un componente fittizio che raccoglie le sue uscite. `init(test)` viene chiamato quando il flusso è pronto, con l'oggetto `test`:

- `test.send(inputid, data)` (anche `test.input`) invia un messaggio a un ingresso del componente e lo restituisce.
- `test.message = function($, data)`: chiamato con ogni messaggio che il componente invia a **una qualsiasi delle sue uscite**; `$` è il messaggio e `data` i suoi dati.
- `test.reconfigure(config)` cambia la configurazione; `test.configure = function(config)` viene chiamato dopo. `test.variables(object)` imposta le variabili del flusso.
- `test.assert(ok, message)`, `test.ok(message)` e `test.fail(message)` stampano `[OK]` o `[NO]` con la data, e un fallimento genera un'eccezione. Le funzioni sono semplici proprietà: sostituisci `test.ok` e `test.fail` per inviare il risultato altrove, come fa l'esempio.
- Il flusso di test ha sempre l'id `test`: un solo `Flow.test()` alla volta.

È pensato per i test di un componente scritto per un Flow, eseguiti con `node index.js` in una piccola applicazione a parte.

```js definitions/component-test.js
MAIN.results = [];

const source = `<script total>
exports.id = 'tax';
exports.name = 'Tax';
exports.inputs = [{ id: 'input', name: 'Input' }];
exports.outputs = [{ id: 'output', name: 'Output' }];
exports.config = { rate: 21 };
exports.make = function(instance, config) {
	instance.message = function($) {
		$.send('output', { net: $.data, total: Math.round($.data * (100 + config.rate)) / 100 });
	};
};
</script>`;

ON('ready', function() {
	Flow.test('tax', source, { rate: 10 }, function(test) {

		test.ok = message => MAIN.results.push('ok: ' + message);
		test.fail = message => MAIN.results.push('no: ' + message);

		test.message = function($, data) {
			test.assert(data.net === 100, 'the net amount comes back');
			test.assert(data.total === 110, 'the configuration of the test (10 %) is used, got ' + data.total);
			MAIN.results.push('message: ' + JSON.stringify(data));
		};

		test.send('input', 100);
	});
});
```

```js controllers/results.js
exports.install = function() {
	ROUTE('GET /results/', results);
};

function results($) {
	$.json(MAIN.results);
}
```
