打字稿中的 Sinon 存根私有变量?
Sinon stub private variable in typescript?
我想在 class
中存入一个私有变量
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));
}
}
如何在 class 中存入私有变量 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])
})
您可以使用类型断言 来访问私有变量。喜欢:
(ipc as any).publisher
无法存根私有变量,这不是正确的方法,您可以查看下面与 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)
})
我想在 class
中存入一个私有变量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));
}
}
如何在 class 中存入私有变量 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])
})
您可以使用类型断言 来访问私有变量。喜欢:
(ipc as any).publisher
无法存根私有变量,这不是正确的方法,您可以查看下面与 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)
})