const request = require("supertest");
const jwt = require("jsonwebtoken");
const app = require("../app");
jest.mock("../models/flightsModel");
const flightsModel = require("../models/flightsModel");
const validToken = jwt.sign(
{ sub: 1, username: "alice" },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);
beforeEach(() => { jest.clearAllMocks(); });
describe("POST /flights", () => {
const validBody = { origin: "Seoul", destination: "Tokyo", duration: 120 };
test("returns 401 when no Authorization header is sent", async () => {
const res = await request(app).post("/flights").send(validBody);
expect(res.statusCode).toBe(401);
expect(flightsModel.create).not.toHaveBeenCalled();
});
test("returns 400 when the body is missing required fields", async () => {
const res = await request(app)
.post("/flights")
.set("Authorization", `Bearer ${validToken}`)
.send({ origin: "Seoul", destination: "Tokyo" });
expect(res.statusCode).toBe(400);
expect(flightsModel.create).not.toHaveBeenCalled();
});
test("returns 201 with the created flight when token and body are valid", async () => {
const created = { id: 42, ...validBody };
flightsModel.create.mockResolvedValue(created);
const res = await request(app)
.post("/flights")
.set("Authorization", `Bearer ${validToken}`)
.send(validBody);
expect(res.statusCode).toBe(201);
expect(res.body).toEqual(created);
});
});