Skip to content
Snippets Groups Projects
Commit 3cc2de4e authored by Daniel Fott's avatar Daniel Fott Committed by Lucendio
Browse files

Create tests for the authentication middleware

parent 573fac18
No related branches found
No related tags found
No related merge requests found
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);
});
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment