Node-RED Node Test Helper

0.3.6 · active · verified Sun Apr 19

The Node-RED Node Test Helper is a comprehensive framework designed for unit testing Node-RED nodes and flows. It enables developers to start a dedicated Node-RED runtime instance within their test environment, load specific test flows, and simulate message injection and reception to verify node behavior. The current stable version is 0.3.6, with regular maintenance updates including dependency bumps and minor feature enhancements. This helper differentiates itself by integrating directly with the Node-RED runtime, providing a realistic testing environment that goes beyond simple JavaScript unit tests, ensuring nodes function correctly within the flow-based programming paradigm. It is an essential tool for maintaining the quality and reliability of custom Node-RED nodes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic unit test for a custom Node-RED node, loading a flow, injecting messages, and asserting the output, including proper asynchronous handling.

import helper from 'node-red-node-test-helper';
import should from 'should';
import path from 'path';

// Assuming your node is in ../my-awesome-node.js relative to the test file
const myAwesomeNode = require(path.resolve(__dirname, '../my-awesome-node.js'));

// Initialize the helper to locate the Node-RED runtime
helper.init(require.resolve('node-red'));

describe('My Awesome Node', function () {

  beforeEach(async function () {
      await helper.startServer();
  });

  afterEach(async function () {
      await helper.unload();
      await helper.stopServer();
  });

  it('should be loaded correctly', async function () {
    const flow = [{ id: 'n1', type: 'my-awesome-node', name: 'test node' }];
    await helper.load(myAwesomeNode, flow);
    const n1 = helper.getNode('n1');
    n1.should.have.property('name', 'test node');
  });

  it('should process input and send expected output', async function () {
    const flow = [
      { id: 'n1', type: 'my-awesome-node', name: 'test node', wires:[['n2']] },
      { id: 'n2', type: 'helper' }
    ];
    await helper.load(myAwesomeNode, flow);
    const n2 = helper.getNode('n2');
    const n1 = helper.getNode('n1');

    const promise = new Promise((resolve, reject) => {
      n2.on('input', function (msg) {
        try {
          msg.should.have.property('payload', 'processed value');
          resolve();
        } catch(err) {
          reject(err);
        }
      });
    });

    n1.receive({ payload: 'initial value' });
    await promise;
  });
});

view raw JSON →