-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.test.js
More file actions
66 lines (65 loc) · 2.06 KB
/
api.test.js
File metadata and controls
66 lines (65 loc) · 2.06 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
import { deepStrictEqual, ok, strictEqual } from "node:assert";
import { after, before, describe, it } from "node:test";
describe("API Workflow", () => {
let _server = {};
let _globalToken = "";
const BASE_URL = "http://localhost:3000";
before(async () => {
_server = (await import("./api.js")).app;
if (!_server.listening) {
await new Promise((resolve) => {
_server.once("listening", resolve);
});
}
});
after((done) => _server.close(done));
it("should received not authorized given wrong user and password", async () => {
const data = {
user: "leonardojaques",
password: "",
};
const request = await fetch(`${BASE_URL}/login`, {
method: "POST",
body: JSON.stringify(data),
});
strictEqual(request.status, 401);
const response = await request.json();
deepStrictEqual(response, { error: "user or password invalid" });
});
it("should login successfully given user and password", async () => {
const data = {
user: "leonardojaques",
password: "123",
};
const request = await fetch(`${BASE_URL}/login`, {
method: "POST",
body: JSON.stringify(data),
});
strictEqual(request.status, 200);
const response = await request.json();
ok(response.token, "token should be present");
_globalToken = response.token;
});
it("should not be allowed to access private data without a token", async () => {
const request = await fetch(`${BASE_URL}/`, {
method: "GET",
headers: {
authorization: "",
},
});
strictEqual(request.status, 401);
const response = await request.json();
deepStrictEqual(response, { error: "invalid token!" });
});
it("should be allowed to access private data with a valid token", async () => {
const request = await fetch(`${BASE_URL}/`, {
method: "GET",
headers: {
authorization: `Bearer ${_globalToken}`,
},
});
strictEqual(request.status, 200);
const response = await request.json();
deepStrictEqual(response, { result: "Hey welcome" });
});
});