-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathmessageRoutes.test.js
More file actions
79 lines (66 loc) · 2.45 KB
/
messageRoutes.test.js
File metadata and controls
79 lines (66 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import test from "node:test";
import assert from "node:assert/strict";
import { createApp } from "../app.js";
import { signAccessToken } from "../utils/jwt.js";
const messagePayload = {
recipientId: "usr_freelancer",
body: "Can we discuss the project timeline?"
};
async function withServer(callback) {
const app = createApp();
const server = app.listen(0);
await new Promise((resolve, reject) => {
server.once("listening", resolve);
server.once("error", reject);
});
try {
const { port } = server.address();
await callback(`http://127.0.0.1:${port}`);
} finally {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
}
test("message routes reject unauthenticated requests", async () => {
await withServer(async (baseUrl) => {
const getResponse = await fetch(`${baseUrl}/api/messages`);
const getPayload = await getResponse.json();
assert.equal(getResponse.status, 401);
assert.equal(getPayload.success, false);
assert.equal(getPayload.message, "Unauthorized");
const postResponse = await fetch(`${baseUrl}/api/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(messagePayload)
});
const postPayload = await postResponse.json();
assert.equal(postResponse.status, 401);
assert.equal(postPayload.success, false);
assert.equal(postPayload.message, "Unauthorized");
});
});
test("message routes allow authenticated send and list requests", async () => {
await withServer(async (baseUrl) => {
const token = signAccessToken({ sub: "usr_client", role: "client" });
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
};
const postResponse = await fetch(`${baseUrl}/api/messages`, {
method: "POST",
headers,
body: JSON.stringify(messagePayload)
});
const postPayload = await postResponse.json();
assert.equal(postResponse.status, 201);
assert.equal(postPayload.success, true);
assert.equal(postPayload.data.body, messagePayload.body);
assert.ok(postPayload.data.id);
const getResponse = await fetch(`${baseUrl}/api/messages`, { headers });
const getPayload = await getResponse.json();
assert.equal(getResponse.status, 200);
assert.equal(getPayload.success, true);
assert.ok(getPayload.data.some((message) => message.id === postPayload.data.id));
});
});