Skip to content

Commit 5ee8d40

Browse files
authored
Merge pull request #80 from Luke-Manyamazi/tests/login-tests
added login tests
2 parents 42173c2 + 1966361 commit 5ee8d40

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

api/__tests__/login.test.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { describe, it, expect, beforeEach } from "vitest";
2+
3+
import db from "../db.js";
4+
5+
import { createRequest } from "./testUtils.js";
6+
7+
describe("Authentication - Login", () => {
8+
beforeEach(async () => {
9+
// Clear users table before each test
10+
await db.query("DELETE FROM users");
11+
});
12+
13+
describe("POST /api/auth/login", () => {
14+
it("should return 401 if the user does not exist", async () => {
15+
const request = await createRequest();
16+
17+
const response = await request
18+
.post("/api/auth/login")
19+
.send({ email: "nobody@example.com", password: "Password123!" })
20+
.expect(401);
21+
22+
expect(response.body.message).toBe("Invalid credentials.");
23+
});
24+
25+
it("should return 401 if the password is incorrect", async () => {
26+
const request = await createRequest();
27+
28+
// First create a user
29+
const userData = {
30+
name: "John Doe",
31+
email: "john@example.com",
32+
password: "Password123!",
33+
};
34+
await request.post("/api/auth/signup").send(userData).expect(201);
35+
36+
// Attempt login with wrong password
37+
const response = await request
38+
.post("/api/auth/login")
39+
.send({ email: "john@example.com", password: "WrongPassword!" })
40+
.expect(401);
41+
42+
expect(response.body.message).toBe("Invalid credentials.");
43+
});
44+
45+
it("should return 200 and a token when credentials are correct", async () => {
46+
const request = await createRequest();
47+
48+
// Signup first
49+
const userData = {
50+
name: "Jane Doe",
51+
email: "jane@example.com",
52+
password: "Password123!",
53+
};
54+
await request.post("/api/auth/signup").send(userData).expect(201);
55+
56+
// Login with correct credentials
57+
const response = await request
58+
.post("/api/auth/login")
59+
.send({ email: "jane@example.com", password: "Password123!" })
60+
.expect(200);
61+
62+
expect(response.body).toHaveProperty("token");
63+
expect(response.body).toHaveProperty("user");
64+
expect(response.body.user).toHaveProperty("id");
65+
expect(response.body.user).toHaveProperty("name", userData.name);
66+
expect(response.body.user).toHaveProperty(
67+
"email",
68+
userData.email.toLowerCase(),
69+
);
70+
});
71+
});
72+
});

0 commit comments

Comments
 (0)