简体   繁体   English

使用Typescript和Sinon在单例类中测试静态方法

[英]Test static method in singleton class with Typescript and Sinon

I have a DAO class as a separate layer for getting data from my repository. 我有一个DAO类作为从存储库中获取数据的单独层。 I made the class Singleton and methods static. 我将类Singleton和方法设为静态。

In another class I made other service methods for transforming the data. 在另一堂课中,我提出了用于转换数据的其他服务方法。 I would like to write tests for this code but don't succeed. 我想为此代码编写测试,但不会成功。

How to mock the Dao repository methods? 如何模拟Dao存储库方法?

This is what I tried so far: 这是我到目前为止尝试过的:

// 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);
        }
    }
}

Solved it like this: 像这样解决它:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM