2017-07-18 128 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); 
相关问题