Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2020
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require('dotenv').config();
  2.  
  3. const httpMocks = require('node-mocks-http');
  4. const auth = require('../../middlewares/auth');
  5. const jwt = require('jsonwebtoken');
  6.  
  7. jwt.verify = jest.fn();
  8.  
  9. let req, res, next;
  10.  
  11. beforeEach(() => {
  12.     req = httpMocks.createRequest();
  13.     res = httpMocks.createResponse();
  14.     next = jest.fn();
  15. });
  16.  
  17. describe('auth middleware', () => {
  18.     beforeEach(() => {
  19.         req.headers.auth = 'some_token';
  20.         req.params.userId = 'some_user_id';
  21.     });
  22.     it('should return 401 to requests without a token', async () => {
  23.         req.headers.auth = undefined;
  24.         await auth(req, res, next);
  25.         expect(res.statusCode).toBe(401);
  26.     });
  27.     it('should return 401 to requests with invalid tokens', async () => {
  28.         req.headers.auth = 'not a valid token';
  29.         // This is returning undefined too
  30.         jest.mock('jsonwebtoken/verify', () => new Error());
  31.         await auth(req, res, next);
  32.         expect(res.statusCode).toBe(401);        
  33.     });
  34.     it('should call next when everything is ok', async () => {
  35.         req.headers.auth = 'rgfh4hs6hfh54sg46';
  36.         jest.mock('jsonwebtoken/verify', (tokenHeader, secret) => {
  37.             return jest.fn(() => ({ id: 'rgfh4hs6hfh54sg46' }));
  38.         });
  39.         await auth(req, res, next);
  40.         expect(next).toBeCalled();
  41.     });
  42. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement