Test a Flow component alone with Flow.test()
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)(alsotest.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 anddataits 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)andtest.fail(message)print[OK]or[NO]with the date, and a failure throws. The functions are plain properties: replacetest.okandtest.failto send the result somewhere else, as the example does.- The test flow always has the id
test: only oneFlow.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.
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);
});
});exports.install = function() {
ROUTE('GET /results/', results);
};
function results($) {
$.json(MAIN.results);
}