2017-02-22 59 views
0

我想存根類Sinon stub私有變量在打字稿中?

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]) 
}) 

回答

0

有沒有辦法來,踩私有變量,而這是不這樣做的正確的方式,你可以看到下面的討論與基督教約翰森

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) 
}) 
0

您可以使用類型斷言,以獲得訪問私有變量。像:

(ipc as any).publisher 
+0

但我怎能ST UB呢? – Tim

+0

您的意思是:'sinon.stub(ipc,'publisher');'? –

+0

我想測試我的代碼,如上圖所示,但我無法實現它,它會抱怨'不能讀取屬性'的getCall'的undefined',所以我不知道如何實現我想要的測試.. – Tim