Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require('dotenv').config();
- const httpMocks = require('node-mocks-http');
- const auth = require('../../middlewares/auth');
- const jwt = require('jsonwebtoken');
- jwt.verify = jest.fn();
- let req, res, next;
- beforeEach(() => {
- req = httpMocks.createRequest();
- res = httpMocks.createResponse();
- next = jest.fn();
- });
- describe('auth middleware', () => {
- beforeEach(() => {
- req.headers.auth = 'some_token';
- req.params.userId = 'some_user_id';
- });
- it('should return 401 to requests without a token', async () => {
- req.headers.auth = undefined;
- await auth(req, res, next);
- expect(res.statusCode).toBe(401);
- });
- it('should return 401 to requests with invalid tokens', async () => {
- req.headers.auth = 'not a valid token';
- // This is returning undefined too
- jest.mock('jsonwebtoken/verify', () => new Error());
- await auth(req, res, next);
- expect(res.statusCode).toBe(401);
- });
- it('should call next when everything is ok', async () => {
- req.headers.auth = 'rgfh4hs6hfh54sg46';
- jest.mock('jsonwebtoken/verify', (tokenHeader, secret) => {
- return jest.fn(() => ({ id: 'rgfh4hs6hfh54sg46' }));
- });
- await auth(req, res, next);
- expect(next).toBeCalled();
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement