Skip to content

Commit

Permalink
Merge pull request #540 from Financial-Times/matth/catch-app-context-…
Browse files Browse the repository at this point in the history
…error

Handle validation errors gracefully in app context middleware
  • Loading branch information
i-like-robots authored Aug 6, 2019
2 parents b7834e0 + 386b75c commit 0ac134e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
26 changes: 24 additions & 2 deletions packages/dotcom-middleware-app-context/src/__test__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
jest.mock('@financial-times/dotcom-server-app-context')

import httpMocks from 'node-mocks-http'
import { AppContext } from '@financial-times/dotcom-server-app-context'
import { init } from '../index'
Expand All @@ -12,8 +14,6 @@ const headers = {
'ft-ab': '-'
}

jest.mock('@financial-times/dotcom-server-app-context')

describe('dotcom-middleware-app-context', () => {
let instance
let request
Expand All @@ -27,6 +27,10 @@ describe('dotcom-middleware-app-context', () => {
instance = init({ context })
})

afterEach(() => {
jest.resetAllMocks()
})

it('returns a request handler function', () => {
expect(instance).toBeInstanceOf(Function)
expect(instance).toHaveLength(3)
Expand Down Expand Up @@ -71,4 +75,22 @@ describe('dotcom-middleware-app-context', () => {
expect(next).toHaveBeenCalled()
})
})

describe('when the context data is invalid', () => {
beforeEach(() => {
// NOTE: AppContext has been mocked but we must first
// tell TS it's a mock before we can use it like one.
const AppContextMock = AppContext as jest.Mock

AppContextMock.mockImplementation(() => {
throw Error('INVALID')
})
})

it('calls the fallthrough function with the error', () => {
instance(request, response, next)

expect(next).toHaveBeenCalledWith(expect.any(Error))
})
})
})
6 changes: 5 additions & 1 deletion packages/dotcom-middleware-app-context/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export function init(options: TMiddlewareOptions = {}) {
...options.context
}

response.locals.appContext = new AppContext({ context })
try {
response.locals.appContext = new AppContext({ context })
} catch (error) {
next(error)
}

next()
}
Expand Down

0 comments on commit 0ac134e

Please sign in to comment.