Skip to content

Commit

Permalink
getPosts
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 20, 2023
1 parent cbe8b68 commit cae8417
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 1 deletion.
53 changes: 53 additions & 0 deletions __test__/controllers/posts/getPosts.controller.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { type Request, type Response } from "express";
import Post from "../../../src/models/post.model";
import { getPosts } from "../../../src/controllers/posts";

// Mocking the Post model
jest.mock("../../../src/models/post.model", () => ({
find: jest.fn().mockReturnThis(),
exec: jest.fn(),
}));

describe("post controller", () => {
describe("getPosts", () => {
let req: Request;
let res: Response;

beforeEach(() => {
res = {
send: jest.fn(),
sendStatus: jest.fn(),
} as unknown as Response;
});

afterEach(() => {
jest.clearAllMocks();
});

test("should retrieve and send posts", async () => {
const posts = [{ title: "Post 1" }, { title: "Post 2" }];

// Mocking the Post.find().exec() method to return posts
(Post.find().exec as jest.Mock).mockResolvedValue(posts);

await getPosts(req, res);

expect(res.send).toHaveBeenCalledWith(posts);
expect(res.sendStatus).not.toHaveBeenCalled();
});

test("should send 500 status on error", async () => {
const errorMessage = "Internal server error";

// Mocking the Post.find().exec() method to throw an error
(Post.find().exec as jest.Mock).mockRejectedValue(
new Error(errorMessage)
);

await getPosts(req, res);

expect(res.sendStatus).toHaveBeenCalledWith(500);
expect(res.send).not.toHaveBeenCalled();
});
});
});
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "env-cmd nodemon ./src/index.ts",
"test": "jest"
"test": "jest",
"prettier": "npx prettier --write .",
"lint": "npx eslint ."
},
"repository": {
"type": "git",
Expand Down
15 changes: 15 additions & 0 deletions src/controllers/posts/getPosts.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { type Request, type Response } from "express";
import Post from "../../models/post.model";

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const getPosts = async (_req: Request, res: Response) => {
try {
const query = Post.find({});
const posts = await query.exec();
res.send(posts);
} catch (error) {
res.sendStatus(500);
}
};

export default getPosts;
3 changes: 3 additions & 0 deletions src/controllers/posts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import getPosts from "./getPosts.controller";

export { getPosts };

0 comments on commit cae8417

Please sign in to comment.