Testing a MQTT node in a Node-RED flow using Mocha and node-red-node-test-helper node


Hello everyone, I'm trying to test a Node-RED flow using Mocha and node-red-node-test-helper node.
More specifically, I would like to test something like the enclosed subflow, by simulating/mocking a message sent from a mqtt out node not part of the subflow (e.g. because in another tab) that the mqtt in node part of the subflow should receive and trasmit to next nodes for proper testing purposes (e.g. checking that the received values is equal to a certain value).

The code I have implemented so far is the following, although I am not sure how to simulate sending/receiving messages.

var should = require(“should”);
var mqttNode = require("./10-mqtt.js");
var functionNode = require("./80-function.js");
var helper = require(“node-red-node-test-helper”);

describe(‘post’, function() {

    before(function(done) {

    after(function(done) {

    afterEach(function() {

    it('should receive a value via mqtt', function(done) {
        var flow = [{id:"49298d89.2ebe54",type:"mqtt-broker",z:"",broker:"iot.eclipse.org",port:"1883",clientid:"",usetls:false,compatmode:true,keepalive:"60",cleansession:true,willTopic:"",willQos:"0",willPayload:"",birthTopic:"",birthQos:"0",birthPayload:""}, {id:"da68f37c.cbf9c",type:"mqtt in",z:"40096806.2e352",name:"myMQTTNode",topic:"test/mytopic",qos:"2",broker:"49298d89.2ebe54",x:2610,y:700,wires:[["2cce5779.320728"]]},			{id:"2cce5779.320728",type:"function",z:"40096806.2e352",name:"myFunctionNode",func:"console.log(msg); return msg;",outputs:1,noerr:0,x:2920,y:640,wires:["helper"]},			{id:"helper",type:"helper",z:"40096806.2e352",name:"myHelper",active:true,tosidebar:true,console:false,tostatus:false,complete:"false",x:1560,y:340,wires:[]}];

        helper.load([functionNode, mqttNode], flow, function() {
	     var n1 = helper.getNode("helper");
	     n1.on("input", function(msg) {
		     msg.should.have.property('payload', 'value');




Did you find a solution? Would be curious to know about this too.



You are almost there. The trick is to disregard the mqtt node and "manually" send the message:

var n2 = helper.getNode("2cce5779.320728"); // myFunctionNode
n2.receive({payload:"The payload that the mqtt node would send goes here..."}); // n2 receives this message and executes

Add this code after you registered the "input" event handler.

1 Like