使用sinon来存根String.prototype getter方法

时间:2017-09-28 15:11:41

标签: javascript unit-testing mocha sinon chai

我有一个场景,我需要在String.prototype上存根一个getter方法。在这种情况下,由NPM模块colors定义的方法。

it('should only apply colors if enable in the .ENV file', function () {
    var stringGreyStub = sinon.stub(String.prototype, 'grey').get(function(){
        console.log('FAKE!');
    });
    Log.setLevel(1);
    Log.log('Message to log.', 1);
    console.log(stringGreyStub.called);
});

上述测试的输出是:

FAKE!
[28/Sep/2017:08:06:13-0700] This is some message to be logged!
false

据我所知,正在调用存根,因为正在记录FAKE!。但是,stringGreyStub.called的值仍为false。我有什么想法可能做错了吗?

1 个答案:

答案 0 :(得分:0)

这似乎只是sinon在吸气剂和制定者方面发挥作用的方式。解决方案是使用存根来获取实际的getter值,并检查是否调用了它。

it('should only apply colors if enable in the .ENV file', function () {
    var getterStub = sinon.stub();
    sinon.stub(String.prototype, 'grey').get(getterStub);
    Log.setLevel(1);
    Log.log('Message to log.', 1);
    console.log(getterStub.called);
});

该解决方案见于以下github问题。

https://github.com/sinonjs/sinon/issues/1545