Newer
Older
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
const auth = require('../middlewares/auth');
const jwt = require('jsonwebtoken');
const { model: Users } = require('../models/Users');
describe('Testing the authorization middleware', () => {
let mockRequest;
let mockResponse;
let nextFunction = jest.fn();
const token = 'mytoken';
beforeEach(() => {
mockRequest = {
cookies: {
'todo-jt': token,
}
};
mockResponse = {
redirect: jest.fn(),
status: jest.fn(() => {
return {
send: jest.fn()
}
})
};
});
test('should redirect, if the value of the todo-jt cookie is an empty string', async () => {
mockRequest.cookies['todo-jt'] = '';
auth(mockRequest, mockResponse, nextFunction);
expect(mockResponse.redirect).toHaveBeenCalledWith(401, '/login');
});
test('should save the found user and token in the request', async () => {
const mockUser = {
username: 'testname',
password: 'testpw'
};
jest.spyOn(jwt, 'verify').mockReturnValue(token);
jest.spyOn(Users, 'findOne').mockResolvedValue(mockUser);
await auth(mockRequest, mockResponse, nextFunction);
expect(mockRequest.token).toEqual(token)
expect(mockRequest.user).toEqual(mockUser);
});
test('should sent a 401 status code, if the user could not be found', async () => {
spyOn(jwt, 'verify').mockReturnValue(token);
spyOn(Users, 'findOne').mockResolvedValue(undefined);
await auth(mockRequest, mockResponse, nextFunction);
expect(mockRequest.user).toBeUndefined;
expect(mockResponse.status).toHaveBeenCalledWith(401);
});
});