# Test a Flow component alone with Flow.test()

> Load one component in a flow of its own, send it a message from the code and read what it sends to its outputs, without building the whole flow.

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

`Flow.test(name, source, [config], [init])` builds a flow with **one** component (the `source` is its code, like in the recipe of FlowStream, and `config` replaces its configuration) and a dummy component that collects its outputs. `init(test)` is called when the flow is ready, with the object `test`:

- `test.send(inputid, data)` (also `test.input`) sends a message to an input of the component and returns it.
- `test.message = function($, data)`: called with every message that the component sends to **any of its outputs**; `$` is the message and `data` its data.
- `test.reconfigure(config)` changes the configuration; `test.configure = function(config)` is called after it. `test.variables(object)` sets the variables of the flow.
- `test.assert(ok, message)`, `test.ok(message)` and `test.fail(message)` print `[OK]` or `[NO]` with the date, and a failure throws. The functions are plain properties: replace `test.ok` and `test.fail` to send the result somewhere else, as the example does.
- The test flow always has the id `test`: only one `Flow.test()` at a time.

It is meant for the tests of a component that is written for a Flow, run with `node index.js` in a small application of its own.

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