Skip to content

Commit

Permalink
test: add CookieStore helper class to store cookies for auth'd routes
Browse files Browse the repository at this point in the history
  • Loading branch information
karrui committed Sep 2, 2020
1 parent 9819a39 commit 4852630
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/app/modules/auth/__tests__/auth.routes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { pick } from 'lodash'
import supertest from 'supertest'
import { setupApp } from 'tests/integration/helpers/express-setup'
import { CookieStore, setupApp } from 'tests/integration/helpers/express-setup'
import dbHandler from 'tests/unit/backend/helpers/jest-db'
import validator from 'validator'

Expand All @@ -14,12 +14,14 @@ import * as AuthService from '../auth.service'

describe('auth.routes', () => {
const app = setupApp('/auth', AuthRouter)
const cookieStore = new CookieStore()
const request = supertest(app)

beforeAll(async () => await dbHandler.connect())
afterEach(async () => {
await dbHandler.clearDatabase()
jest.restoreAllMocks()
cookieStore.clear()
})
afterAll(async () => await dbHandler.closeDatabase())

Expand Down Expand Up @@ -420,6 +422,7 @@ describe('auth.routes', () => {
const response = await request
.post('/auth/verifyotp')
.send({ email: VALID_EMAIL, otp: MOCK_VALID_OTP })
cookieStore.handleCookie(response)

// Assert
expect(response.status).toEqual(200)
Expand All @@ -431,6 +434,8 @@ describe('auth.routes', () => {
created: expect.any(String),
email: VALID_EMAIL,
})
// Should have session cookie returned.
expect(cookieStore.get()).toEqual(expect.stringContaining('connect.sid'))
})

it('should return 500 when upserting user document fails', async () => {
Expand Down
28 changes: 28 additions & 0 deletions tests/integration/helpers/express-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import compression from 'compression'
import express, { Router } from 'express'
import helmet from 'helmet'
import mongoose from 'mongoose'
import { Response } from 'supertest'

import errorHandlerMiddlewares from 'src/loaders/express/error-handler'
import helmetMiddlewares from 'src/loaders/express/helmet'
Expand Down Expand Up @@ -33,3 +34,30 @@ export const setupApp = (

return app
}

/**
* Helper class to store cookies for routes that require authorization.
* @example
* request
.post('/some/route/that/requires/auth')
.set('cookie', cookieStore.get());
*/
export class CookieStore {
#currentCookie: string = ''

handleCookie(res: Response) {
this.set(res.header['set-cookie'][0])
}

set(cookie: string) {
this.#currentCookie = cookie
}

get() {
return this.#currentCookie
}

clear() {
this.#currentCookie = ''
}
}

0 comments on commit 4852630

Please sign in to comment.