2017-07-18 10 views
0

私のリポジトリからデータを取得するための別のレイヤーとしてDAOクラスがあります。私はクラスSingletonとメソッドstaticを作った。TypescriptとSinonを使ったシングルトンクラスでの静的メソッドのテスト

別のクラスでは、データを変換するための他のサービスメソッドを作成しました。私はこのコードのテストを書いてみたいが、成功しない。

Daoリポジトリメソッドを模擬する方法は?

これは私がこれまで試したものです:

// 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); 
関連する問題