-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.test.js
88 lines (80 loc) · 2.18 KB
/
server.test.js
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
80
81
82
83
84
85
86
87
88
const app = require('./server');
const supertest = require('supertest');
const user = { name: 'joe', age: 20 };
// Start with an empty users array
test('GET /api/users', async () => {
await supertest(app)
.get('/api/users')
.expect(200)
.then((res) => {
expect(Array.isArray(res.body.users)).toBeTruthy();
expect(res.body.users.length).toEqual(0);
});
});
// Add new user to that array
test('POST /api/users', async () => {
await supertest(app)
.post('/api/users')
.send(user)
.expect(201)
.then((res) => {
expect(res.body.name).toBe(user.name);
expect(res.body.age).toBe(user.age);
// Save the user id for testing in later steps
user.id = res.body.id;
});
});
// Test if the user has been added
test('GET /api/user/:id', async () => {
await supertest(app)
.get(`/api/user/${user.id}`)
.expect(200)
.then((res) => {
expect(res.body.name).toBe(user.name);
expect(res.body.age).toBe(user.age);
});
});
// Test if the array contains that user
test('GET /api/users', async () => {
await supertest(app)
.get('/api/users')
.expect(200)
.then((res) => {
expect(Array.isArray(res.body.users)).toBeTruthy();
expect(res.body.users.length).toEqual(1);
expect(res.body.users[0].name).toBe(user.name);
expect(res.body.users[0].age).toBe(user.age);
});
});
// Update that specific user
test('PUT /api/user/:id', async () => {
user.age++;
await supertest(app)
.put(`/api/user/${user.id}`)
.send(user)
.expect(200)
.then((res) => {
expect(res.body.name).toBe(user.name);
expect(res.body.age).toBe(user.age);
});
});
// Delete that user
test('DELETE /api/user/:id', async () => {
await supertest(app)
.delete(`/api/user/${user.id}`)
.expect(200)
.then((res) => {
expect(res.body.name).toBe(user.name);
expect(res.body.age).toBe(user.age);
});
});
// Now the users array should be empty again
test('GET /api/users', async () => {
await supertest(app)
.get('/api/users')
.expect(200)
.then((res) => {
expect(Array.isArray(res.body.users)).toBeTruthy();
expect(res.body.users.length).toEqual(0);
});
});