-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticationController.test.js
81 lines (63 loc) · 1.99 KB
/
authenticationController.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
const crypto = require('crypto');
const {
hashPassword,
areCredentialsValid,
authenticationMiddleware
} = require('./authenticationController');
const { user } = require('./userTestUtils')
// Unit testing
describe('hashPassword', () => {
test('hashing password', () => {
const plainTextPassword = 'azerty123';
const hash = crypto.createHash("sha256");
hash.update(plainTextPassword);
const expectedHash = hash.digest("hex");
const actualHash = hashPassword(plainTextPassword);
expect(actualHash).toEqual(expectedHash);
});
});
describe('authenticationMiddleware', () => {
test('returns an error with invalid credentials', async () => {
const fakeAuth = Buffer.from('invalid:credentials').toString("base64");
const req = {
headers: {
authorization: `Basic ${fakeAuth}`
}
};
const res = {};
const next = jest.fn();
await authenticationMiddleware(req, res, next);
expect(next.mock.calls).toHaveLength(0);
expect(res).toEqual({
...res,
status: 401,
error: { message: 'Please provide valid credentials' }
})
});
test('calls next with valid credentials', async () => {
const req = {
headers: {
authorization: user.authHeader
}
};
const res = {};
const next = jest.fn();
await authenticationMiddleware(req, res, next);
expect(next.mock.calls).toHaveLength(1);
});
});
// Integration testing
describe('areCredentialsValid', () => {
test('valid credentials', async () => {
const hasValidCredentials = await areCredentialsValid(user.username, user.password);
expect(hasValidCredentials).toBe(true);
});
test('invalid credentials', async () => {
const hasValidCredentials = await areCredentialsValid(user.username, 'qsdfgh456');
expect(hasValidCredentials).toBe(false);
});
test('user does not exist', async () => {
const result = await areCredentialsValid('test_user_not_existing', 'azerty123');
expect(result).toBe(false);
});
});