node-red / node-red-node-test-helper

A test framework for Node-RED nodes
Apache License 2.0
57 stars 40 forks source link

please provide documentation how to init context #55

Open dumdiedum opened 1 year ago

dumdiedum commented 1 year ago

I can't find a documentation how to init context while testing. Only what I found is this: https://discourse.nodered.org/t/how-can-i-access-global-context-in-tests/51820 which links to https://github.com/node-red/node-red/blob/master/test/nodes/core/function/15-change_spec.js#L31

So I'm trying to load Context to use global context beyond testcases (inject/debug pairs) with

var Context = require('../node_modules/@node-red/runtime/lib/nodes/context');
function initContext(done) {
    Context.init({
        contextStorage: {
            memory0: {
                module: 'memory',
            },
            memory1: {
                module: 'memory',
            },
        },
    });
    Context.load().then(function () {
        done();
    });
}

I using before/after hook as following:

before(function (done) {
    initContext(done); // context should now be available for all testcases within describe
});
beforeEach(function (done) {
    helper.startServer(done);
});

afterEach(function (done) {
    helper.unload().then(function () {
        helper.stopServer(done);
    });
});
after(function (done) { // not sure if this is correct
    Context.clean({ allNodes: {} }).then(function () {
        return Context.close();
    });
    done();
});

and then the tests will be performed:

describe("Test", () => {
...
}

My testing flows contains to testcases:

  1. Stores data in global context
  2. Data in global context should be available (via global.get)

I would now expect that both testcases are ok, but second testcase is not successful. I'm pretty sure the context is not used correctly, but I can't find a example in this repo. Can you please help me with this?