10

我想对以下简化模块进行单元测试:

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
};

我正在logplease使用Proxyquire替换外部依赖项,效果很好。但是我需要存根two(),因为我想进行单元测试,同时消除在实际代码中运行时产生one()的副作用。two()

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();
});

我得到的输出:

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

我期望的输出:

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

为什么我的存根函数不运行?

4

1 回答 1

1

简短的回答:

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;

解释:范围

您将一和二导出为:

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

在这种情况下tester.one只知道这个函数:

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

并且不知道存根两个。所以你有两个版本的two只需尝试在 test中调用tester.two()

于 2017-02-20T15:18:40.377 回答