lukaswilkeer

jwt mock doens't get called

May 12th, 2020
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // auth.test.js
  2. import mocha from 'mocha';
  3. import sinon from 'sinon';
  4. import { expect } from 'chai';
  5. import client from 'socket.io-client';
  6. import jwt from 'json-web-token';
  7. import '../index.js';
  8.  
  9. afterEach(() => {
  10.     sinon.restore();
  11. });
  12.  
  13. describe.only('Connection', () => {
  14.     it('should connect to the socket server', (done) => {
  15.         const authStub = sinon.stub(jwt, 'decode').callsFake((secret, payload, callback) => {
  16.             console.log('secret', secret);
  17.             console.log('payload', payload);
  18.             console.log('callback', callback);
  19.             return callback(null, {data: 'someuser'});
  20.         });
  21.  
  22.         const connection = new client(`http://localhost:${process.env.PORT}`);
  23.  
  24.         expect(authStub.called).to.be.true();
  25.         expect(connection.connected).to.be.true();
  26.  
  27.         connection.on('message', (data) => {
  28.             expect(typeof data).to.be.equals('string');
  29.             done();
  30.         });
  31.     });
  32. });
  33.  
  34.  
  35. // lib/auth.js
  36.  
  37. import jwt from 'json-web-token';
  38.  
  39. const secret = 'some secret key, prefer .pem files';
  40.  
  41. const decode = (payload) => jwt.decode(secret, payload, (err, data) => {
  42.     return !err ? data : err;
  43. });
  44.  
  45. const auth = (headers, socket) => {
  46.     let authorization;
  47.  
  48.     if (headers.authorization !== undefined) {
  49.         authorization = headers.authorization;
  50.     } else {
  51.         authorization = null;
  52.     }
  53.  
  54.     if (!(decode(authorization) instanceof Error)) {
  55.         socket.emit('message', 'client connected');
  56.         return true;
  57.     } else {
  58.         socket.emit('message', 'client unauthorized');
  59.         return false;
  60.     }
  61. };
  62.  
  63. export default auth;
Add Comment
Please, Sign In to add comment