stubbing a function in a proxyquired object
Asked Answered
C

1

10

I want to unit-test the following simplified module:

const Logger = require('logplease');
const logger = Logger.create('utils');

const tester = {

    one: () => {
        logger.log('called real one()');
        tester.two();
    },
    two: () => {
        logger.log('called real two()');
    },
};

module.exports = {
    one: tester.one,
    two: tester.two
};

I'm replacing the external dependency logplease using Proxyquire, which works very well. However I need to stub two() because I want to unit-test one() while eliminating the side-effects two() produces when it runs in real code.

it.only('stubbing functions on the "proxyquired" object under test', function(done) {

    const loggerStub = {
        create: () => {
            return { log: (msg) => { console.log('fake logger: ', msg); } };
        }
    };

    let tester = proxyquire('../tester', { 'logplease': loggerStub });

    let stub2 = sinon.stub(
        tester, 
        'two', 
        () => { 
            console.log('called fake stub of two()'); 
        }
    );

    tester.one();

    console.log('call count 2: ', stub2.callCount);
    done();
});

Output I get:

fake logger:  called real one() 
fake logger:  called real two() 
call count 2: 0

Output I expect:

fake logger:  called real one() 
called fake stub of two()
call count 2: 1

Why doesn't my stub function run?

Chainman answered 10/2, 2017 at 21:36 Comment(1)
I may have found my answer: #35111867Chainman
K
1

Short answer:

const Logger = require('logplease');
const logger = Logger.create('utils');

const tester = {

    one: () => {
        logger.log('called real one()');
        tester.two();
    },
    two: () => {
        logger.log('called real two()');
    },
};

module.exports = tester;

Explanation: scope

You exported one and two as:

module.exports = {
    one: tester.one,
    two: tester.two
};

In this case tester.one knows only about this function:

two: () => {
    logger.log('called real two()');
}

and have no idea about stubbed two. So you have two versions of two, just try to invoke tester.two() inside test.

Kilimanjaro answered 20/2, 2017 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.