I have a separate layer in my application that uses a DAO class to retrieve data from the repository. I've implemented the DAO class as a Singleton and made its methods static.
In another class, I've created service methods to manipulate the data obtained from the DAO. However, I'm having trouble writing tests for this code.
How can I mock the DAO repository methods?
This is what I have attempted 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);
}
}
}