-
Notifications
You must be signed in to change notification settings - Fork 196
/
basic-tests.test.js
263 lines (225 loc) · 7.66 KB
/
basic-tests.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const axios = require('axios');
const sinon = require('sinon');
const nock = require('nock');
const { initializeWebServer, stopWebServer } = require('../entry-points/api');
const OrderRepository = require('../data-access/order-repository');
// Configuring file-level HTTP client with base URL will allow
// all the tests to approach with a shortened syntax
let axiosAPIClient;
beforeAll(async () => {
// ️️️✅ Best Practice: Place the backend under test within the same process
const apiConnection = await initializeWebServer();
const axiosConfig = {
baseURL: `http://127.0.0.1:${apiConnection.port}`,
validateStatus: () => true, //Don't throw HTTP exceptions. Delegate to the tests to decide which error is acceptable
};
axiosAPIClient = axios.create(axiosConfig);
// ️️️✅ Best Practice: Ensure that this component is isolated by preventing unknown calls
const hostname = '127.0.0.1';
nock.disableNetConnect();
nock.enableNetConnect(hostname);
// Some http clients swallow the "no match" error, so throw here for easy debugging
nock.emitter.on('no match', (req) => {
if (req.hostname !== hostname) {
throw new Error(`Nock no match for: ${req.hostname}`)
}
})
});
beforeEach(() => {
nock('http://localhost/user/').get(`/1`).reply(200, {
id: 1,
name: 'John',
});
});
afterEach(() => {
nock.cleanAll();
sinon.restore();
});
afterAll(async () => {
// ️️️✅ Best Practice: Clean-up resources after each run
await stopWebServer();
nock.enableNetConnect();
});
// ️️️✅ Best Practice: Structure tests
describe('/api', () => {
describe('GET /order', () => {
test('When asked for an existing order, Then should retrieve it and receive 200 response', async () => {
//Arrange
const orderToAdd = {
userId: 1,
productId: 2,
mode: 'approved',
};
const {
data: { id: addedOrderId },
} = await axiosAPIClient.post(`/order`, orderToAdd);
//Act
// ️️️✅ Best Practice: Use generic and reputable HTTP client like Axios or Fetch. Avoid libraries that are coupled to
// the web framework or include custom assertion syntax (e.g. Supertest)
const getResponse = await axiosAPIClient.get(`/order/${addedOrderId}`);
//Assert
expect(getResponse).toMatchObject({
status: 200,
data: {
userId: 1,
productId: 2,
mode: 'approved',
},
});
});
test('When asked for an non-existing order, Then should receive 404 response', async () => {
//Arrange
const nonExistingOrderId = -1;
//Act
const getResponse = await axiosAPIClient.get(
`/order/${nonExistingOrderId}`
);
//Assert
expect(getResponse.status).toBe(404);
});
});
describe('POST /orders', () => {
// ️️️✅ Best Practice: Check the response
test('When adding a new valid order, Then should get back approval with 200 response', async () => {
//Arrange
const orderToAdd = {
userId: 1,
productId: 2,
mode: 'approved',
};
//Act
const receivedAPIResponse = await axiosAPIClient.post(
'/order',
orderToAdd
);
//Assert
expect(receivedAPIResponse).toMatchObject({
status: 200,
data: {
id: expect.any(Number),
mode: 'approved',
},
});
});
// ️️️✅ Best Practice: Check the new state
// In a real-world project, this test can be combined with the previous test
test('When adding a new valid order, Then should be able to retrieve it', async () => {
//Arrange
const orderToAdd = {
userId: 1,
productId: 2,
mode: 'approved',
};
//Act
const {
data: { id: addedOrderId },
} = await axiosAPIClient.post('/order', orderToAdd);
//Assert
const { data, status } = await axiosAPIClient.get(
`/order/${addedOrderId}`
);
expect({
data,
status,
}).toMatchObject({
status: 200,
data: {
id: addedOrderId,
userId: 1,
productId: 2,
},
});
});
// ️️️✅ Best Practice: Check external calls
test('When adding a new valid order, Then an email should be send to admin', async () => {
//Arrange
process.env.SEND_MAILS = 'true';
// ️️️✅ Best Practice: Intercept requests for 3rd party services to eliminate undesired side effects like emails or SMS
// ️️️✅ Best Practice: Specify the body when you need to make sure you call the 3rd party service as expected
let emailPayload;
nock('http://mailer.com')
.post('/send', (payload) => ((emailPayload = payload), true))
.reply(202);
const orderToAdd = {
userId: 1,
productId: 2,
mode: 'approved',
};
//Act
await axiosAPIClient.post('/order', orderToAdd);
//Assert
// ️️️✅ Best Practice: Assert that the app called the mailer service appropriately
expect(emailPayload).toMatchObject({
subject: expect.any(String),
body: expect.any(String),
recipientAddress: expect.stringMatching(
/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
),
});
});
// ️️️✅ Best Practice: Check invalid input
test('When adding an order without specifying product, stop and return 400', async () => {
//Arrange
const orderToAdd = {
userId: 1,
mode: 'draft',
};
//Act
const orderAddResult = await axiosAPIClient.post('/order', orderToAdd);
//Assert
expect(orderAddResult.status).toBe(400);
});
// ️️️✅ Best Practice: Check error handling
test.todo('When a new order failed, an invalid-order error was handled');
// ️️️✅ Best Practice: Check monitoring metrics
test.todo(
'When a new valid order was added, then order-added metric was fired'
);
// ️️️✅ Best Practice: Simulate external failures
test.todo(
'When the user service is down, then order is still added successfully'
);
test('When the user does not exist, return 404 response', async () => {
//Arrange
nock('http://localhost/user/').get(`/7`).reply(404, null);
const orderToAdd = {
userId: 7,
productId: 2,
mode: 'draft',
};
//Act
const orderAddResult = await axiosAPIClient.post('/order', orderToAdd);
//Assert
expect(orderAddResult.status).toBe(404);
});
test('When order failed, send mail to admin', async () => {
//Arrange
process.env.SEND_MAILS = 'true';
// ️️️✅ Best Practice: Intercept requests for 3rd party services to eliminate undesired side effects like emails or SMS
// ️️️✅ Best Practice: Specify the body when you need to make sure you call the 3rd party service as expected
let emailPayload;
nock('http://mailer.com')
.post('/send', (payload) => ((emailPayload = payload), true))
.reply(202);
sinon
.stub(OrderRepository.prototype, 'addOrder')
.throws(new Error('Unknown error'));
const orderToAdd = {
userId: 1,
productId: 2,
mode: 'approved',
};
//Act
await axiosAPIClient.post('/order', orderToAdd);
//Assert
// ️️️✅ Best Practice: Assert that the app called the mailer service appropriately
expect(emailPayload).toMatchObject({
subject: expect.any(String),
body: expect.any(String),
recipientAddress: expect.stringMatching(
/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
),
});
});
});
});