Search code examples
node.jstestingsinonstubsinon-chai

How to stub an inner function and set a variable value


This is one of the more complex scenarios I've encountered yet. I have a function that I need to test, this function is nested in a complex puzzle of functions. I need to stub this function, and set a value inside the variable inside.

For reasons I'm not allowed to share here, the variable inside the publishEvent() method is undefined during test run, I need a way to set the value for this variable during test in order for me to test the if block of code in the function.

I summarized the whole file because I can't share the code here due to NDA, sorry if the question is not detailed enough. Maybe using sinon I can directly set the value for this variable in the publishEvent function.

function emitEvent() {
    async function publishEvent() {
        const variable = library.fetchData()

        if (variable) {
            // do something
        }
    }

    return Promise.resolve(publishEvent())
            .then(() => { })
            .catch(() => null);
}

function requestSuscription() {
    return getAllSubscriptions()
        .then((results) => {
            return Promise.map(results, () => emitEvent())
        })
}

function getAllSubscriptions() {
    return new Promise()
}

function requestOtherSubscription() {
    console.log('other thing requested')
}

module.exports = { requestSuscription, requestOtherSubscription }

I know I can stub the requestSuscription, requestOtherSubscription functions and it works, but how can I stub the publishEvent and set the variable value?


Solution

  • You need a way of controlling what library.fetchData() outputs. Either you need a way of injecting a substitute for that library (easiest option) or you need to employ a link seam (environment dependant, requires extra lib) - substituting the library with a fake one at the module loading level.

    You can check out this SO answer to a nearly identical question for details.