### startServer(done) Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Starts a Node-RED server instance for testing HTTP or WebSocket endpoints. ```APIDOC ## startServer(done) ### Description Starts a Node-RED server specifically for testing purposes. This is necessary for nodes that interact with HTTP or WebSocket endpoints, such as the debug node. ### Method `helper.startServer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript before(function(done) { helper.startServer(done); }); ``` ### Response Calls the provided `done` callback function upon successful server startup. No direct return value. ``` -------------------------------- ### Example Unit Test for Lower-Case Node Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md A comprehensive example demonstrating how to write unit tests for a Node-RED node using the test helper. It covers initialization, server start/stop, node loading, and message handling. ```javascript var should = require("should"); var helper = require("node-red-node-test-helper"); var lowerNode = require("../lower-case.js"); helper.init(require.resolve('node-red')); describe('lower-case Node', function () { beforeEach(function (done) { helper.startServer(done); }); afterEach(function (done) { helper.unload(); helper.stopServer(done); }); it('should be loaded', function (done) { var flow = [{ id: "n1", type: "lower-case", name: "lower-case" }]; helper.load(lowerNode, flow, function () { var n1 = helper.getNode("n1"); try { n1.should.have.property('name', 'lower-case'); done(); } catch(err) { done(err); } }); }); it('should make payload lower case', function (done) { var flow = [ { id: "n1", type: "lower-case", name: "lower-case",wires:[["n2"]] }, { id: "n2", type: "helper" } ]; helper.load(lowerNode, flow, function () { var n2 = helper.getNode("n2"); var n1 = helper.getNode("n1"); n2.on("input", function (msg) { try { msg.should.have.property('payload', 'uppercase'); done(); } catch(err) { done(err); } }); n1.receive({ payload: "UpperCase" }); }); }); }); ``` -------------------------------- ### Start and Stop HTTP Server Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use `startServer()` and `stopServer()` to manage the HTTP server for testing nodes that rely on HTTP endpoints or WebSockets. Ensure `helper.init()` is called before starting the server. ```javascript var helper = require("node-red-node-test-helper"); var httpInNode = require("./nodes/http-in.js"); helper.init(require.resolve('node-red')); describe('HTTP node tests', function() { before(function(done) { helper.startServer(done); }); after(function(done) { helper.stopServer(done); }); afterEach(function() { helper.unload(); }); it('should respond to HTTP request', function(done) { var flow = [ { id: "n1", type: "http in", url: "/test", method: "get", wires: [["n2"]] }, { id: "n2", type: "http response" } ]; helper.load(httpInNode, flow, function() { helper.request() .get('/test') .expect(200) .end(done); }); }); // Using async/await it('should respond to HTTP request (async)', async function() { await helper.startServer(); var flow = [{ id: "n1", type: "http in", url: "/api", method: "post" }]; await helper.load(httpInNode, flow); await helper.request() .post('/api') .send({ data: 'test' }) .expect(200); await helper.stopServer(); }); }); ``` -------------------------------- ### API: `helper.load()` Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Documentation for the `helper.load()` function, used to load and start Node-RED flows for testing. ```APIDOC ## API: `helper.load()` ### Description Loads a flow then starts the flow. This function is essential for setting up the testing environment by loading the node and flow data. ### Method `helper.load(testNode, testFlows, testCredentials, cb)` ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **testNode** (object|array of objects) - Module object of a node to be tested returned by require function. This node will be registered, and can be used in testFlows. - **testFlows** (array of objects) - Flow data to test a node. If you want to use flow data exported from Node-RED editor, export the flow to the clipboard and paste the content into your test scripts. - **testCredentials** (object) - Optional node credentials. - **cb** (function) - Function to call back when testFlows has been started (not required when called with `await`). ### Request Example ```javascript // Example usage within a test helper.load(MyNode, flowData, credentials, function() { // Flow loaded and started, proceed with tests }); ``` ### Response #### Success Response (200) N/A (This is a function call, not an HTTP request) #### Response Example N/A ``` -------------------------------- ### Start Node-RED Server Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Starts a Node-RED server for testing nodes that rely on HTTP or Web Sockets. Typically called once before all test cases. ```javascript before(function(done) { helper.startServer(done); }); ``` -------------------------------- ### Install Node Test Helper and Node-RED Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Add the test helper and Node-RED as development dependencies to your node project using npm. ```bash npm install node-red-node-test-helper node-red --save-dev ``` -------------------------------- ### Node Initialization Warning Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md This node warns if a configuration property 'somethingGood' is not provided during initialization. Use this to test node setup and error handling. ```javascript // /path/to/foo-node.js module.exports = function FooNode (config) { RED.nodes.createNode(this, config); if (!config.somethingGood) { this.warn('badness'); } } ``` -------------------------------- ### Load Test Flows with Node Red Test Helper Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use `load()` to register test nodes, load a flow definition, and start the flow. It accepts node modules, flow arrays, optional credentials, and can return a Promise or use a callback. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); describe('my-node', function() { afterEach(function() { helper.unload(); }); it('should be loaded', function(done) { var flow = [{ id: "n1", type: "my-node", name: "test-node" }]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); n1.should.have.property('name', 'test-node'); done(); }); }); // Using async/await syntax it('should be loaded (async)', async function() { var flow = [{ id: "n1", type: "my-node", name: "test-node" }]; await helper.load(myNode, flow); var n1 = helper.getNode("n1"); n1.should.have.property('name', 'test-node'); }); // Loading with credentials it('should load with credentials', function(done) { var flow = [{ id: "n1", type: "my-node", name: "test-node" }]; var credentials = { n1: { username: "admin", password: "secret" } }; helper.load(myNode, flow, credentials, function() { done(); }); }); }); ``` -------------------------------- ### Get Test Server URL Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `helper.url()` method returns the full URL of the test server, including the ephemeral port. This is useful for making direct HTTP requests to the test server during integration tests. ```javascript var helper = require("node-red-node-test-helper"); helper.init(require.resolve('node-red')); describe('Server URL tests', function() { before(function(done) { helper.startServer(done); }); after(function(done) { helper.stopServer(done); }); it('should return server URL', function() { var url = helper.url(); // Returns something like "http://127.0.0.1:54321" url.should.match(/^http:\/\/127\.0\.0\.1:\d+$/); console.log('Test server running at:', url); }); }); ``` -------------------------------- ### Update Node-RED Flows at Runtime Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `setFlows()` method allows updating the flow configuration after initial load, which is useful for testing dynamic flow changes. This example demonstrates loading an initial flow, then updating it to include the node under test. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); it('should modify the flow then process message', async function() { // Initial flow with just a helper node var flow = [ { id: "n2", type: "helper" } ]; await helper.load(myNode, flow); // Update flow to add the node under test var newFlow = [...flow]; newFlow.push({ id: "n1", type: "lower-case", name: "lower-case", wires: [['n2']] }); await helper.setFlows(newFlow, "nodes"); var n1 = helper.getNode('n1'); n1.should.have.property('name', 'lower-case'); await new Promise((resolve, reject) => { var n2 = helper.getNode('n2'); n2.on('input', function(msg) { try { msg.should.have.property('payload', 'hello'); resolve(); } catch(err) { reject(err); } }); n1.receive({ payload: 'HELLO' }); }); }); ``` -------------------------------- ### Full Server Lifecycle Management Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Manages the full lifecycle of the Node-RED test server, including starting before tests and stopping after all tests are complete. `unload()` is called after each test for cleanup. ```javascript // Using with stopServer describe('Full server lifecycle', function() { before(function(done) { helper.startServer(done); }); afterEach(function(done) { helper.unload().then(function() { done(); }); }); after(function(done) { helper.stopServer(done); }); }); ``` -------------------------------- ### Node-RED Input Field HTML Source: https://github.com/node-red/node-red-node-test-helper/blob/master/examples/nodes/lower-case.html Defines an HTML input field for a Node-RED node's configuration panel. This example shows a text input for the node's name. ```html
``` -------------------------------- ### Inspect Node Logs Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use the `log()` method to get a spy on the logging system, allowing inspection of log messages generated by nodes during testing. Filter logs by node type or level to verify specific messages. ```javascript var helper = require("node-red-node-test-helper"); var functionNode = require("./nodes/80-function.js"); helper.init(require.resolve('node-red')); describe('Log inspection', function() { afterEach(function() { helper.unload(); }); it('should log an error message', function(done) { var flow = [ { id: "n1", type: "function", wires: [[]], func: "node.error('Something went wrong'); return msg;" } ]; helper.load(functionNode, flow, function() { var n1 = helper.getNode("n1"); n1.receive({ payload: "test" }); // Check that log was called helper.log().called.should.be.true(); // Filter for specific node type var logEvents = helper.log().args.filter(function(evt) { return evt[0].type === "function"; }); logEvents.should.have.length(1); var msg = logEvents[0][0]; msg.should.have.property('level', helper.log().ERROR); msg.should.have.property('id', 'n1'); msg.should.have.property('type', 'function'); msg.should.have.property('msg', 'Something went wrong'); done(); }); }); it('should verify warning was logged', function(done) { var flow = [{ id: "n1", type: "function", func: "node.warn('Deprecated usage');" }]; helper.load(functionNode, flow, function() { var n1 = helper.getNode("n1"); n1.receive({}); var warnings = helper.log().args.filter(function(evt) { return evt[0].level === helper.log().WARN; }); warnings.should.have.length(1); warnings[0][0].msg.should.equal('Deprecated usage'); done(); }); }); }); ``` -------------------------------- ### Initialize Node Red Test Helper Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Call `init()` before loading test flows. It configures the helper with the Node-RED runtime path and optional user settings like global context. ```javascript var helper = require("node-red-node-test-helper"); // Basic initialization - auto-discovers Node-RED helper.init(require.resolve('node-red')); // With custom settings (e.g., global context for function nodes) helper.init(require.resolve('node-red'), { functionGlobalContext: { os: require('os'), moment: require('moment') } }); ``` -------------------------------- ### Initialize Node Test Helper Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Initialize the test helper by providing the path to the Node-RED runtime. An optional user settings object can be passed to merge with runtime defaults. ```javascript helper.init(require.resolve('node-red')); ``` ```javascript helper.init(require.resolve('node-red'), { functionGlobalContext: { os:require('os') } }); ``` -------------------------------- ### Creating Test Flows with Helper Nodes Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Illustrates how to define test flows using JavaScript objects, including specifying node types, IDs, and wiring. It shows how to use a 'helper' node and how to replace 'debug' nodes with 'helper' nodes when exporting flows from the editor. ```javascript var flow = [{id:"f1", type:"tab", label:"Test flow"}, { id: "n1", z:"f1", type: "lower-case", name: "test name",wires:[["n2"]] }, { id: "n2", z:"f1", type: "helper" } ``` -------------------------------- ### Asynchronous Testing with `call:` Events Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Demonstrates how to test asynchronous method calls (like `warn`) by listening for `call:` events emitted by the helper. ```APIDOC ## Testing Asynchronous Method Calls ### Description This section explains how to test asynchronous method calls, such as `warn`, which are not immediately executed. The test helper emits a `call:` event when the spy is called, allowing for asynchronous assertions. ### Method Event Listener ### Endpoint `call:` (e.g., `call:warn`) ### Parameters #### Event Parameters - **call** (object) - A Spy Call object containing details of the method call. ### Request Example ```javascript describe('if `somethingBadAndWeird` in input msg', function () { it('should call "warn" with "bad weirdness" ', function (done) { const flow = { name: 'n1', /* ..etc.. */ }; helper.load(FooNode, flow, function () { const n1 = helper.getNode('n1') n1.receive({somethingBadAndWeird: true}); // because the emit happens asynchronously, this listener // will be registered before `call:warn` is emitted. n1.on('call:warn', call => { call.should.be.calledWithExactly('bad weirdness'); done(); }); }); }); }); ``` ### Response #### Event Emission (Asynchronous) - The `call:` event is emitted asynchronously after the spy method is called. - The event passes a single argument: a Spy Call object. #### Response Example ```json { "example": "Spy Call object" } ``` ``` -------------------------------- ### Simulate Node Input and Check Output Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Send a message to a node under test and verify its output by attaching an event handler to a mock helper node. Ensure the helper node is loaded after the node under test. ```javascript n1.receive({ payload: "UpperCase" }); ``` -------------------------------- ### Configure Runtime Settings for Tests Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `settings()` method merges custom settings with Node-RED defaults, enabling features like `functionGlobalContext` for function nodes. Configure global context before loading nodes and reset settings after the test. ```javascript var helper = require("node-red-node-test-helper"); var functionNode = require("./nodes/80-function.js"); helper.init(require.resolve('node-red')); it('should access functionGlobalContext', function(done) { var flow = [ { id: "n1", type: "function", wires: [["n2"]], func: "msg.payload = global.get('foo'); return msg;" }, { id: "n2", type: "helper" } ]; // Configure global context before loading helper.settings({ functionGlobalContext: { foo: 'bar', myModule: require('lodash') } }); helper.load(functionNode, flow, function() { var n1 = helper.getNode("n1"); var n2 = helper.getNode("n2"); n2.on("input", function(msg) { msg.should.have.property('payload', 'bar'); done(); }); n1.receive({ payload: "test" }); }); // Reset settings after test helper.settings({}); }); ``` -------------------------------- ### url() Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Returns the URL of the helper server, including the dynamically assigned ephemeral port. ```APIDOC ## url() ### Description Retrieves the complete URL for the running Node-RED test server, including the host and the ephemeral port that was assigned when the server started. ### Method `helper.url` ### Endpoint N/A (This is a utility function, not an HTTP endpoint) ### Parameters None ### Request Example ```javascript const serverUrl = helper.url(); console.log('Test server is running at:', serverUrl); ``` ### Response Returns a string representing the URL of the test server (e.g., 'http://127.0.0.1:1337'). ``` -------------------------------- ### settings(userSettings) Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Merges user-defined settings with the default Node-RED settings for the test environment. Each call overwrites previous settings. ```APIDOC ## settings(userSettings) ### Description Allows modification of Node-RED settings within the test environment by merging provided `userSettings` with the default settings. This is useful for replicating specific environment configurations, such as global context variables. ### Method `helper.settings` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **userSettings** (object) - Required - An object containing the settings to merge or override. For example, `{ functionGlobalContext: { os: require('os') } }`. ### Request Example ```javascript // Enable access to the 'os' module in function nodes helper.settings({ functionGlobalContext: { os: require('os') } }); // Reset settings back to defaults (or previous state if called multiple times) helper.settings({}); ``` ### Response This function modifies the test environment's settings and does not return a value. ``` -------------------------------- ### Configure User Settings Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Merges user-defined settings with default Node-RED settings. Useful for replicating production environments, such as enabling global context modules. ```javascript // functions can now access os via global.get('os') helper.settings({ functionGlobalContext: { os:require('os') } }); ``` ```javascript // reset back to defaults helper.settings({ }); ``` -------------------------------- ### request() Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Creates an HTTP request using the 'supertest' library to interact with the Node-RED editor or admin interface. ```APIDOC ## request() ### Description Provides an interface to create HTTP requests to the Node-RED editor/admin URL, utilizing the 'supertest' library for testing. ### Method `helper.request` ### Endpoint N/A (This function returns a request object that can be used to define endpoints) ### Parameters None ### Request Example ```javascript // Example: Making a POST request to an invalid inject endpoint and expecting a 404 helper.request().post('/inject/invalid').expect(404).end(done); ``` ### Response Returns a 'supertest' request object that allows chaining of HTTP methods (GET, POST, PUT, DELETE, etc.) and assertions. ``` -------------------------------- ### Test Node Message Flow with Helper Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use the helper node to capture and inspect messages output from the node under test. Wire it to your node's outputs and listen for 'input' events. Ensure the helper node is unloaded after each test. ```javascript var helper = require("node-red-node-test-helper"); var lowerCaseNode = require("../lower-case.js"); helper.init(require.resolve('node-red')); describe('lower-case node', function() { afterEach(function() { helper.unload(); }); it('should make payload lower case', function(done) { var flow = [ { id: "n1", type: "lower-case", name: "lower-case", wires: [["n2"]] }, { id: "n2", type: "helper" } ]; helper.load(lowerCaseNode, flow, function() { var n1 = helper.getNode("n1"); var n2 = helper.getNode("n2"); // Listen for messages on the helper node n2.on("input", function(msg) { try { msg.should.have.property('payload', 'hello world'); done(); } catch(err) { done(err); } }); // Send a message into the node under test n1.receive({ payload: "HELLO WORLD" }); }); }); it('should handle multiple outputs', function(done) { var flow = [ { id: "n1", type: "splitter", wires: [["n2"], ["n3"]] }, { id: "n2", type: "helper" }, { id: "n3", type: "helper" } ]; helper.load(splitterNode, flow, function() { var n1 = helper.getNode("n1"); var n2 = helper.getNode("n2"); var n3 = helper.getNode("n3"); var count = 0; n2.on("input", function(msg) { msg.should.have.property('payload', 'output1'); count++; if (count === 2) done(); }); n3.on("input", function(msg) { msg.should.have.property('payload', 'output2'); count++; if (count === 2) done(); }); n1.receive({ payload: "test" }); }); }); }); ``` -------------------------------- ### Testing Asynchronous Spy Calls with Node Test Helper Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Shows how to test asynchronous spy calls (like `warn`) using the node test helper. It listens for a 'call:warn' event emitted by the helper, which is triggered when the spy is called, allowing for assertions on the call details. ```javascript describe('if `somethingBadAndWeird` in input msg', function () { it('should call "warn" with "bad weirdness" ', function (done) { const flow = { name: 'n1', /* ..etc.. */ }; helper.load(FooNode, flow, function () { const n1 = helper.getNode('n1') n1.receive({somethingBadAndWeird: true}); // because the emit happens asynchronously, this listener // will be registered before `call:warn` is emitted. n1.on('call:warn', call => { call.should.be.calledWithExactly('bad weirdness'); done(); }); }); }); }); ``` -------------------------------- ### Test Node Initialization Warning Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Assert that the `warn` function is called with the correct message when a node is initialized without the 'somethingGood' configuration property. This tests synchronous initialization logic. ```javascript // /path/to/test/foo-node_spec.js const FooNode = require('/path/to/foo-node'); it('should warn if the `somethingGood` prop is falsy', function (done) { const flow = { name: 'n1', somethingGood: false, /* ..etc.. */ }; helper.load(FooNode, flow, function () { n1.warn.should.be.calledWithExactly('badness'); done(); }); }); ``` -------------------------------- ### Make HTTP Request Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Creates an HTTP request to the Node-RED editor/admin URL using supertest. Use this to test API endpoints. ```javascript helper.request().post('/inject/invalid').expect(404).end(done); ``` -------------------------------- ### Asynchronous Warn Call in Node Input Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Demonstrates an asynchronous call to `this.warn()` within a Node-RED node's input listener using a Promise. This pattern requires special handling in tests due to its asynchronous nature. ```javascript this.on('input', msg => { if (msg.omg) { this.error('lolwtf'); } // ..etc.. Promise.resolve() .then(() => { if (msg.somethingBadAndWeird) { this.warn('bad weirdness'); } }); }); ``` -------------------------------- ### Make HTTP Requests to Admin API Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `request()` method returns a supertest instance for making HTTP requests to the admin API endpoints. Use this to test node behavior that interacts with the Node-RED API. ```javascript var helper = require("node-red-node-test-helper"); helper.init(require.resolve('node-red')); describe('Admin API tests', function() { before(function(done) { helper.startServer(done); }); after(function(done) { helper.stopServer(done); }); it('should return 404 for invalid endpoint', function(done) { helper.request() .post('/inject/invalid') .expect(404) .end(done); }); it('should send POST data', function(done) { helper.request() .post('/my-endpoint') .send({ key: 'value' }) .set('Content-Type', 'application/json') .expect(200) .expect(function(res) { res.body.should.have.property('status', 'ok'); }) .end(done); }); }); ``` -------------------------------- ### Verify Node Status Changes Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use the `on('call:status', ...)` event to verify that the node's status has been updated correctly. This is essential for testing nodes that interact with the status display. ```javascript n1.on('call:status', function(call) { call.should.be.calledWith({ fill: "green", shape: "dot", text: "connected" }); done(); }); ``` -------------------------------- ### Synchronous Spy Assertion Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Use this to verify that a Node.prototype method was called synchronously during initialization. Ensure the node is loaded before making assertions. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); describe('Spy and async event tests', function() { afterEach(function() { helper.unload(); }); // Synchronous spy usage it('should verify warn was called during initialization', function(done) { var flow = [{ id: "n1", type: "my-node", somethingGood: false }]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); // Direct spy assertion n1.warn.should.be.calledWithExactly('badness'); done(); }); }); // Asynchronous event usage for delayed calls it('should detect async warn call', function(done) { var flow = [{ id: "n1", type: "my-node" }]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); // Listen for async method calls n1.on('call:warn', function(call) { call.should.be.calledWithExactly('async warning'); done(); }); n1.receive({ triggerAsyncWarn: true }); }); }); // Verify status changes it('should verify status was set', function(done) { var flow = [{ id: "n1", type: "my-node" }]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); n1.on('call:status', function(call) { call.should.be.calledWith({ fill: "green", shape: "dot", text: "connected" }); done(); }); n1.receive({ connect: true }); }); }); }); ``` -------------------------------- ### Testing Flows with Catch Nodes Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt When testing flows that include `catch` nodes, ensure you define a `tab` node and associate the `catch` node with it using the `z` property. This allows the test helper to correctly route errors. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); describe('Catch and status node tests', function() { afterEach(function() { helper.unload(); }); it('should catch errors from node', function(done) { var flow = [ { id: "f1", type: "tab", label: "Test flow" }, { id: "n1", z: "f1", type: "my-node", name: "test", wires: [[]] }, { id: "n2", z: "f1", type: "catch", wires: [["n3"]] }, { id: "n3", z: "f1", type: "helper" } ]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); var n3 = helper.getNode("n3"); n3.on("input", function(msg) { msg.should.have.property('error'); msg.error.should.have.property('message', 'Test error'); done(); }); n1.receive({ triggerError: true }); }); }); it('should monitor node status changes', function(done) { var flow = [ { id: "f1", type: "tab", label: "Test flow" }, { id: "n1", z: "f1", type: "my-node", wires: [[]] }, { id: "n2", z: "f1", type: "status", wires: [["n3"]] }, { id: "n3", z: "f1", type: "helper" } ]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); var n3 = helper.getNode("n3"); n3.on("input", function(msg) { msg.should.have.property('status'); msg.status.should.have.property('text', 'connected'); done(); }); n1.receive({ connect: true }); }); }); }); ``` -------------------------------- ### Asynchronous Spy Event Detection Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt Listen for asynchronous method calls on a node using the `on('call:', ...)` event. This is useful for verifying actions that occur after an initial event. ```javascript n1.on('call:warn', function(call) { call.should.be.calledWithExactly('async warning'); done(); }); ``` -------------------------------- ### stopServer(done) Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Stops the Node-RED test server. Typically called after `unload()`. ```APIDOC ## stopServer(done) ### Description Stops the Node-RED test server instance. This function is usually called after all test flows have been unloaded to ensure a clean shutdown. ### Method `helper.stopServer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript afterEach(function(done) { helper.unload().then(function() { helper.stopServer(done); }); }); ``` ### Response Calls the provided `done` callback function upon successful server shutdown. No direct return value. ``` -------------------------------- ### unload() Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Stops all flows and cleans up the test runtime, returning a promise. ```APIDOC ## unload() ### Description Stops all active flows and performs cleanup of the test runtime environment. This is typically used to reset the state between tests. ### Method `helper.unload` ### Endpoint N/A (This is a utility function, not an HTTP endpoint) ### Parameters None ### Request Example ```javascript await helper.unload(); ``` ### Response Returns a Promise that resolves when all flows have been stopped and cleanup is complete. ``` -------------------------------- ### log() Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Returns a spy object that allows inspection of log events emitted by nodes under test. ```APIDOC ## log() ### Description Provides access to a spy on the Node-RED logging system, enabling tests to monitor and assert on log messages emitted by the node under test. ### Method `helper.log` ### Endpoint N/A (This is a utility function, not an HTTP endpoint) ### Parameters None ### Request Example ```javascript // Get log events and filter for 'batch' type events const logEvents = helper.log().args.filter(function(event) { return event[0].type == "batch"; }); ``` ### Response Returns a spy object (commonly from a library like Sinon.JS) that captures log calls. The `args` property of the spy can be used to access the arguments passed to the log functions. ``` -------------------------------- ### Testing Node Status Monitoring Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt To test nodes that interact with `status` nodes, define a `tab` and associate the `status` node using the `z` property. This ensures proper message routing for status updates. ```javascript n3.on("input", function(msg) { msg.should.have.property('status'); msg.status.should.have.property('text', 'connected'); done(); }); ``` -------------------------------- ### Retrieve Node Instance by ID Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `getNode()` method retrieves a node instance by its ID from the loaded flow, enabling direct interaction with the node for testing purposes. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); it('should retrieve node properties', function(done) { var flow = [ { id: "n1", type: "my-node", name: "processor", threshold: 10 }, { id: "n2", type: "helper" } ]; helper.load(myNode, flow, function() { var n1 = helper.getNode("n1"); var n2 = helper.getNode("n2"); // Access node properties n1.should.have.property('name', 'processor'); // Access node context n1.context().set("count", 0); n1.context().get("count").should.equal(0); done(); }); }); ``` -------------------------------- ### Add Test Script to package.json Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Include a test script in your package.json to easily run Mocha tests for your Node-RED nodes. ```json "scripts": { "test": "mocha \"test/**/*_spec.js\"" }, ... ``` -------------------------------- ### Test Node Input Error Handling Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Assert that the `error` function is called with the specified message when a node receives an input message containing 'omg: true'. This verifies the node's response to specific input conditions. ```javascript describe('if `omg` in input message', function () { it('should call `error` with "lolwtf" ', function (done) { const flow = { name: 'n1', /* ..etc.. */ }; helper.load(FooNode, flow, function () { const n1 = helper.getNode('n1') n1.receive({omg: true}); n1.on('input', () => { n1.warn.should.be.calledWithExactly('lolwtf'); done(); }); }); }); }); ``` -------------------------------- ### Register Node Type in Node-RED Source: https://github.com/node-red/node-red-node-test-helper/blob/master/examples/nodes/lower-case.html Registers a new node type with Node-RED. This is typically done in a node's definition file. ```javascript RED.nodes.registerType('lower-case',{ category: 'function', color: '#a6bbcf', defaults: { name: {value:""} }, inputs:1, outputs:1, icon: "file.png", label: function() { return this.name||"lower-case"; } }); ``` -------------------------------- ### Load and Modify Flow Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Loads a flow, modifies it by adding a new node, and then updates the flows. Useful for testing node interactions within a dynamic flow. ```javascript it('should modify the flow then lower case of payload', async function () { const flow = [ { id: "n2", type: "helper" } ] await helper.load(lowerNode, flow) const newFlow = [...flow] newFlow.push( { id: "n1", type: "lower-case", name: "lower-case", wires:[['n2']] },) await helper.setFlows(newFlow, "nodes") //update flows const n1 = helper.getNode('n1') n1.should.have.a.property('name', 'lower-case') await new Promise((resolve, reject) => { const n2 = helper.getNode('n2') n2.on('input', function (msg) { try { msg.should.have.property('payload', 'hello'); resolve() } catch (err) { reject(err); } }); n1.receive({ payload: 'HELLO' }); }); }); ``` -------------------------------- ### setFlows(testFlow, type, testCredentials, cb) Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Updates the currently loaded flow with new flow data and optionally node credentials. It can be used with async/await or a callback. ```APIDOC ## setFlows(testFlow, type, testCredentials, cb) ### Description Updates the currently loaded flow with new flow data and optionally node credentials. This function is useful for dynamically changing the flow during tests. ### Method `helper.setFlows` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **testFlow** (array of objects) - Required - Flow data to test a node. Exported from Node-RED editor. * **type** (string) - Required - Specifies the type of flow data. Typically 'nodes'. * **testCredentials** (object) - Optional - Node credentials to be set. * **cb** (function) - Optional - Callback function to be called when flows are loaded. Not required when using `await`. ### Request Example ```javascript // Example using async/await const newFlow = [...flow]; newFlow.push({ id: "n1", type: "lower-case", name: "lower-case", wires:[['n2']] }); await helper.setFlows(newFlow, "nodes"); // Example using callback (less common with modern async/await usage) // helper.setFlows(newFlow, "nodes", null, function(err) { // if (err) throw err; // // flows updated // }); ``` ### Response This function does not return a value directly but modifies the test environment. The callback `cb` is invoked upon completion. ``` -------------------------------- ### clearFlows() Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Stops all active flows in the test environment. ```APIDOC ## clearFlows() ### Description Stops all currently running flows within the Node-RED test environment. ### Method `helper.clearFlows` ### Endpoint N/A (This is a utility function, not an HTTP endpoint) ### Parameters None ### Request Example ```javascript helper.clearFlows(); ``` ### Response This function does not return a value; it performs an action to stop flows. ``` -------------------------------- ### getNode(id) Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Retrieves a node instance from the current test flow by its ID. ```APIDOC ## getNode(id) ### Description Retrieves a specific node instance from the currently loaded test flow using its unique identifier. ### Method `helper.getNode` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **id** (string) - Required - The unique identifier of the node to retrieve. ### Request Example ```javascript const node = helper.getNode('n1'); node.should.have.a.property('name', 'lower-case'); ``` ### Response Returns the node instance object if found, otherwise potentially `undefined` or throws an error depending on implementation details not specified. ``` -------------------------------- ### Node Input Handling with Error Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md This node's input handler calls the `error` function if the incoming message has the 'omg' property set to true. This tests conditional error reporting during message processing. ```javascript // somewhere in FooNode constructor this.on('input', msg => { if (msg.omg) { this.error('lolwtf'); } // ..etc.. }); ``` -------------------------------- ### Filter Log Events Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Returns a spy on logs, allowing you to filter and inspect log events. Useful for verifying node output or behavior through logging. ```javascript var logEvents = helper.log().args.filter(function(event) { return event[0].type == "batch"; }); ``` -------------------------------- ### Stop Node-RED Server Source: https://github.com/node-red/node-red-node-test-helper/blob/master/README.md Stops the Node-RED server. Usually called after unloading flows, often in an afterEach block to clean up after each test. ```javascript afterEach(function(done) { helper.unload().then(function() { helper.stopServer(done); }); }); ``` -------------------------------- ### Unload Flows for Test Isolation Source: https://context7.com/node-red/node-red-node-test-helper/llms.txt The `unload()` method stops flows and cleans up the test runtime. It should be called in `afterEach` to ensure test isolation between tests. ```javascript var helper = require("node-red-node-test-helper"); var myNode = require("../my-node.js"); helper.init(require.resolve('node-red')); describe('Proper cleanup', function() { afterEach(function() { // Always unload to clean up between tests return helper.unload(); }); it('test one', function(done) { var flow = [{ id: "n1", type: "my-node" }]; helper.load(myNode, flow, function() { done(); }); }); it('test two - starts fresh', function(done) { var flow = [{ id: "n1", type: "my-node" }]; helper.load(myNode, flow, function() { // This test runs with a clean state done(); }); }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.