Search code examples
javascriptunit-testingjestjsnode-red

setTimeout error when unit testing a custom node in Node-RED using Jest


I've noticed that in general testing custom nodes in Node-RED is not done using Jest - I don't think there is a particular reason but it's what I'm the most familiar with so I'm trying it anyway.

My test setup looks like

const n = require('../src/index.js');

describe('custom node', () => {
  const nodeType = 'custom node';

  beforeAll(done => {
    helper.startServer(done);
  });

  afterEach(() => {
    helper.unload();
  });

  afterAll(done => {
    helper.stopServer(done);
  });

  it('should be loaded', () =>
    new Promise((resolve, reject) => {
      const flow = [{ id: 'n1', type: nodeType, name: 'test name' }];

      helper.load(n, flow, () => {
        const n1 = helper.getNode('n1');
        try {
          expect(n1).toBeTruthy();
          expect(n1).toHaveProperty('name', 'test name');
          resolve();
        } catch (e) {
          reject(e);
        }
      });
    }));
});

and the error produced is

console.error node_modules/jest-jasmine2/build/jasmine/Env.js:289
      Unhandled error
    console.error node_modules/jest-jasmine2/build/jasmine/Env.js:290
      TypeError: setTimeout(...).unref is not a function
          at Immediate.<anonymous> (/dev/custom_nodes/node-red-contrib-x/node_modules/stoppable/lib/stoppable.js:43:39)
          at processImmediate (internal/timers.js:439:21)
          at process.topLevelDomainCallback (domain.js:126:23)

Solution

  • The solution ended up being simple: set the testEnvironment in Jest config to node so that setTimeout is not replaced by Jest by one which does not have the unref function.

    e.g. in jest.config.js

    module.exports = {
      testEnvironment: 'node',
    };