【问题标题】:Sinon stub private variable in typescript?打字稿中的Sinon存根私有变量?
【发布时间】:2017-07-12 11:13:18
【问题描述】:

我想在一个类中存根一个私有变量

class IPC {
    private publisher: redis.RedisClient;
    constructor() {
        this.publisher = redis.createClient();
    }

    publish(text: string) {
        const msg = {
            text: text
        };

        this.publisher.publish('hello', JSON.stringify(msg));
    }
}

如何在这个类中存根私有变量 publisher ? 所以我可以测试如下所示的代码

it('should return text object', () => {
    const ipc = sinon.createStubInstance(IPC);
    ipc.publish('world!');

    // this will throw error, because ipc.publisher is undefined
    assert.deepStrictEqual({
        text: 'world!'
    }, ipc.publisher.getCall(0).args[0]) 
})

【问题讨论】:

    标签: unit-testing typescript mocha.js sinon stubbing


    【解决方案1】:

    您可以使用 type assertion 来访问私有变量。喜欢:

    (ipc as any).publisher
    

    【讨论】:

    • 但是我怎么能存根呢?
    • 你的意思是:sinon.stub(ipc, 'publisher');?
    • 我想测试我的代码如上图,但我无法实现,它会抱怨Cannot read property 'getCall' of undefined,所以我不知道如何实现我想要的测试..
    • 那么createStubInstance的结果并不是你想的那样。我建议调试ipc
    • 我认为更像是在这种情况下如何测试代码,是否可以实现..
    【解决方案2】:

    没有办法存根私有变量,这不是正确的做法,您可以查看下面与 Christian Johansen 的讨论

    https://groups.google.com/forum/#!topic/sinonjs/ixtXspcamg8

    最好的方法是将任何依赖注入到构造函数中,一旦我们重构代码,我们就可以很容易地用我们需要的行为来存根依赖

    class IPC {    
        constructor(private publisher: redis.RedisClient) {
    
        }
    
    
        publish(text: string) {
            const msg = {
                text: text
            };
    
    
            this.publisher.publish('hello', JSON.stringify(msg));
        }
    }
    
    
    
    it('should return text object', () => {
        sinon.stub(redis, 'createClient')
            .returns({
                publish: sinon.spy()
            });
        const publisherStub = redis.createClient();
    
    
        const ipc = new IPC(publisherStub)
        ipc.publish('world!');
    
    
        // this is working fine now
        assert.deepStrictEqual({
            text: 'world!'
        }, publisherStub.publish.getCall(0).args[0])
    
        sinon.restore(redis.createClient)
    })
    

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 2018-03-04
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2020-10-17
      • 1970-01-01
      • 2019-02-01
      相关资源
      最近更新 更多