-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathmessageValidation.test.js
More file actions
62 lines (55 loc) · 1.8 KB
/
messageValidation.test.js
File metadata and controls
62 lines (55 loc) · 1.8 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
import test from "node:test";
import assert from "node:assert/strict";
import { createApp } from "../app.js";
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();
return await callback(`http://127.0.0.1:${port}`);
} finally {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
}
test("POST /api/messages rejects malformed payloads", async () => {
await withServer(async (baseUrl) => {
const response = await fetch(`${baseUrl}/api/messages`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ fromUserId: "usr_1" })
});
const payload = await response.json();
assert.equal(response.status, 400);
assert.deepEqual(payload, {
success: false,
message: "Invalid message payload"
});
});
});
test("POST /api/messages accepts complete payloads", async () => {
await withServer(async (baseUrl) => {
const response = await fetch(`${baseUrl}/api/messages`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
fromUserId: "usr_1",
toUserId: "usr_2",
body: "Hello"
})
});
const payload = await response.json();
assert.equal(response.status, 201);
assert.equal(payload.success, true);
assert.equal(payload.data.fromUserId, "usr_1");
assert.equal(payload.data.toUserId, "usr_2");
assert.equal(payload.data.body, "Hello");
assert.match(payload.data.id, /^msg_/);
assert.match(payload.data.sentAt, /^\d{4}-\d{2}-\d{2}T/);
});
});