Sinon存根文件中的私有变量?

时间:2017-02-22 12:02:36

标签: unit-testing typescript mocha sinon stubbing

我想在类

中存根私有变量
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]) 
})

2 个答案:

答案 0 :(得分:1)

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

(ipc as any).publisher

答案 1 :(得分:0)

没有办法存根私有变量,这不是正确的方法,你可以在下面与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)
})