Skip to content

Commit

Permalink
index.test.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 21, 2023
1 parent 91f3310 commit 5bba625
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
49 changes: 49 additions & 0 deletions __test__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import mongoose from "mongoose";
import app from "../src/app";
import "../src/workers";

// Mock console.error and console.log
console.error = jest.fn();
console.log = jest.fn();

// Mock mongoose.connect and app.listen
jest.mock("mongoose", () => ({
set: jest.fn(),
connect: jest.fn()
}));
jest.mock("../src/app", () => ({
listen: jest.fn(),
}));
jest.mock("../src/config", () => ({
env: {
MONGODB_URL: "mocked-mongodb-url",
PORT: 3000,
},
}));
jest.mock("../src/workers");

describe("main", () => {
afterEach(() => {
jest.clearAllMocks();
});

it("should connect to MongoDB and start the server", async () => {
await expect(require("../src/index").main()).resolves.not.toThrow()

expect(mongoose.set).toHaveBeenCalledWith("strictQuery", true);
expect(mongoose.connect).toHaveBeenCalledWith("mocked-mongodb-url");
expect(app.listen).toHaveBeenCalledWith(3000, expect.any(Function));
expect(console.error).not.toHaveBeenCalled();
});

it("should handle errors and log them", async () => {
const error = new Error("Connection failed")
mongoose.connect = jest.fn().mockRejectedValueOnce(error)
await expect(require("../src/index").main()).rejects.toThrow(error);

expect(mongoose.connect).toHaveBeenCalledWith("mocked-mongodb-url");
expect(app.listen).not.toHaveBeenCalled();
expect(console.log).not.toHaveBeenCalled();
});
});
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ main().catch((err) => {
console.error(err);
});

async function main(): Promise<void> {
export async function main(): Promise<void> {
await mongoose.connect(env.MONGODB_URL);
app.listen(env.PORT, () => {
console.log(
Expand Down

0 comments on commit 5bba625

Please sign in to comment.