【问题标题】:Using sinon to stub String.prototype getter method使用 sinon 存根 String.prototype getter 方法
【发布时间】:2017-09-28 15:11:40
【问题描述】:

我有一个场景,我需要在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。有什么想法我可能做错了吗?

【问题讨论】:

    标签: javascript unit-testing mocha.js sinon chai


    【解决方案1】:

    这似乎只是 sinon 在 getter 和 setter 中的作用方式。解决方案是为实际的 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

    【讨论】:

    • 如何恢复存根?当我尝试:getterStub.restore() 时,我收到错误:“TypeError: getterStub.restore is not a function”
    猜你喜欢
    • 2015-04-18
    • 2021-06-10
    • 2014-07-17
    • 2014-08-08
    • 2017-07-09
    • 2017-04-27
    • 2016-01-02
    • 2021-04-10
    • 2018-06-20
    相关资源
    最近更新 更多