Unit testing typescript中的Sinon存根私有变量?
我想在类中存根一个私有变量Unit testing typescript中的Sinon存根私有变量?,unit-testing,typescript,mocha.js,sinon,stubbing,Unit Testing,Typescript,Mocha.js,Sinon,Stubbing,我想在类中存根一个私有变量 class IPC { private publisher: redis.RedisClient; constructor() { this.publisher = redis.createClient(); } publish(text: string) { const msg = { text: text }; this.publisher.
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])
})
您可以使用类型断言来访问私有变量。比如:
(ipc as any).publisher
您可以使用类型断言来访问私有变量。比如:
(ipc as any).publisher
没有办法存根私有变量,而且这不是正确的方法,您可以看到下面与Christian Johansen的讨论 最好的方法是将任何依赖项注入构造函数,一旦我们重构代码,我们就可以很容易地用我们所需的行为来存根依赖项
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)
})
没有办法存根私有变量,而且这不是正确的方法,您可以看到下面与Christian Johansen的讨论 最好的方法是将任何依赖项注入构造函数,一旦我们重构代码,我们就可以很容易地用我们所需的行为来存根依赖项
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)
})
但是我怎样才能存根呢?你的意思是:
sinon.stub(ipc,'publisher')代码>?我想按上面所示测试我的代码,但我无法实现,它会抱怨无法读取未定义的属性“getCall”,因此我不知道如何实现我想要的测试..然后createStubInstance
的结果与您想象的不一样。我建议调试ipc
。我认为这更像是在这种情况下如何测试代码,这是可以实现的还是不可以实现的。但是我如何存根它呢?你的意思是:sinon.stub(ipc,'publisher')代码>?我想按上面所示测试我的代码,但我无法实现,它会抱怨无法读取未定义的属性“getCall”,因此我不知道如何实现我想要的测试..然后createStubInstance
的结果与您想象的不一样。我建议调试ipc
。我认为更像是在这种情况下如何测试代码,这是可以实现的还是不可以实现的。。