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

时间:2017-07-18 20:10:24

标签: javascript unit-testing typescript mocha sinon

我有一个DAO类作为从我的存储库中获取数据的单独层。我使类Singleton和方法静态。

在另一个课程中,我提出了其他用于转换数据的服务方法。我想为这段代码编写测试但是没有成功。

如何模拟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);
        }
    }
}

1 个答案:

答案 0 :(得分: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);