2017-07-18 58 views
0

我有一個DAO類作爲從我的存儲庫獲取數據的單獨層。我讓Singleton類和方法是靜態的。使用Typescript和Sinon測試單例類中的靜態方法

在另一個類中,我提出了其他服務方法來轉換數據。我想爲此代碼編寫測試,但不成功。

如何模擬道存儲庫的方法?

這是我試過到目前爲止:

// error: TS2345: Argument of type "getAllPosts" is not assignable to paramenter of type "prototype" | "getInstance" 
const dao = sinon.stub(Dao, "getAllPosts"); 

// TypeError: Attempted to wrap undefined property getAllPosts as function 
const instance = sinon.mock(Dao); 
instance.expects("getAllPosts").returns(data); 

export class Dao { 

    private noPostFound: string = "No post found with id"; 
    private dbSaveError: string = "Error saving to database"; 

    public static getInstance(): Dao { 
     if (!Dao.instance) { 
      Dao.instance = new Dao(); 
     } 
     return Dao.instance; 
    } 

    private static instance: Dao; 
    private id: number; 
    private posts: Post[]; 

    private constructor() { 
     this.posts = posts; 
     this.id = this.posts.length; 
    } 

    public getPostById = (id: number): Post => { 
     const post: Post = this.posts.find((post: Post) => { 
      return post.id === id; 
     }); 

     if (!post) { 
      throw new Error(`${this.noPostFound} ${id}`); 
     } 
     else { 
      return post; 
     } 
    } 

    public getAllPosts =(): Post[] => { 
     return this.posts; 
    } 

    public savePost = (post: Post): void => { 
     post.id = this.getId(); 

     try { 
      this.posts.push(post); 
     } 
     catch(e) { 
      throw new Error(this.dbSaveError); 
     } 
    } 
} 
+0

這裏是上述代碼的測試用例 – muthukumar

回答

0

解決這樣的:

// create an instance of Singleton 
const instance = Dao.getInstance(); 

// mock the instance 
const mock = sinon.mock(instance); 

// mock "getAllPosts" method 
mock.expects("getAllPosts").returns(data); 
相關問題