diff --git a/packages/dotcom-middleware-app-context/src/__test__/index.spec.ts b/packages/dotcom-middleware-app-context/src/__test__/index.spec.ts index 9226ff7f1..b82d34a0d 100644 --- a/packages/dotcom-middleware-app-context/src/__test__/index.spec.ts +++ b/packages/dotcom-middleware-app-context/src/__test__/index.spec.ts @@ -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' @@ -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 @@ -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) @@ -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)) + }) + }) }) diff --git a/packages/dotcom-middleware-app-context/src/index.ts b/packages/dotcom-middleware-app-context/src/index.ts index 53ee35289..f4042b739 100644 --- a/packages/dotcom-middleware-app-context/src/index.ts +++ b/packages/dotcom-middleware-app-context/src/index.ts @@ -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() }