From 423a4652c12cd711b0a81f96e74f060b808bab9f Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Sat, 11 Jun 2022 00:32:51 +0100 Subject: [PATCH] Chipping away at writing the tests --- server/utilities/token-auth.js | 2 +- test/utilities/token-auth.test.js | 87 +++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 test/utilities/token-auth.test.js diff --git a/server/utilities/token-auth.js b/server/utilities/token-auth.js index 40f0a34..9b9a2bd 100644 --- a/server/utilities/token-auth.js +++ b/server/utilities/token-auth.js @@ -3,7 +3,7 @@ const jwt = require('jsonwebtoken'); //middleware to authenticate the JWT token module.exports = (req, res, next) => { const authHeader = req.headers['authorization']; - const token = authHeader?.split (' ')[1]; //'Bearer token' + const token = authHeader?.split(' ')[1]; //'Bearer token' if (!token) { return res.status(401).send('No token found'); diff --git a/test/utilities/token-auth.test.js b/test/utilities/token-auth.test.js new file mode 100644 index 0000000..ac17f0a --- /dev/null +++ b/test/utilities/token-auth.test.js @@ -0,0 +1,87 @@ +describe('token-auth', () => { + beforeEach(() => { + jest.resetModules(); + + //mock out jsonwebtoken + jest.doMock('jsonwebtoken', () => ({ + verify: (token, secretAccess, callback) => { + if (token != 'invalid') { + expect(token).toBe('testtoken'); + return callback(null, { username: 'username' }); + } else { + expect(token).toBe('invalid'); + return callback('Misc. error'); + } + }, + })); + }); + + test('Required Functionality', () => { + const tokenAuth = require('../../server/utilities/token-auth'); + + const req = { + headers: { + authorization: 'Bearer testtoken' + } + }; + + const res = { + status: code => { + expect(code).toBe(null); + return msg => { throw msg; }; + } + }; + + tokenAuth(req, res, () => null); + + expect(req.user.username).toBe('username'); + }); + + test('Missing Token', () => { + const tokenAuth = require('../../server/utilities/token-auth'); + + const req = { + headers: { + // + } + }; + + const res = { + status: code => { + expect(code).toBe(401); + return { + send: msg => { + expect(msg).toBe('No token found'); + return null; + } + }; + } + }; + + tokenAuth(req, res, () => null); + }); + + test('Invalid Token', () => { + const tokenAuth = require('../../server/utilities/token-auth'); + + const req = { + headers: { + authorization: 'Bearer invalid' + } + }; + + const res = { + status: code => { + expect(code).toBe(403); + return { + send: msg => { + expect(msg).toBe('Misc. error'); + return null; + } + }; + } + }; + + tokenAuth(req, res, () => null); + }); +}); \ No newline at end of file