diff --git a/api/src/paths/critter-data/family/index.test.ts b/api/src/paths/critter-data/family/index.test.ts new file mode 100644 index 0000000000..16fdbb3570 --- /dev/null +++ b/api/src/paths/critter-data/family/index.test.ts @@ -0,0 +1,41 @@ +import { expect } from 'chai'; +import sinon from 'sinon'; +import { getFamilies } from '.'; +import { CritterbaseService } from '../../../services/critterbase-service'; +import { getRequestHandlerMocks } from '../../../__mocks__/db'; + +describe('getFamilies', () => { + afterEach(() => { + sinon.restore(); + }); + + it('gets families', async () => { + const mockFamilies = ['family1', 'family2']; + const mockGetFamilies = sinon.stub(CritterbaseService.prototype, 'getFamilies').resolves(mockFamilies); + + const { mockReq, mockRes, mockNext } = getRequestHandlerMocks(); + const requestHandler = getFamilies(); + + await requestHandler(mockReq, mockRes, mockNext); + + expect(mockGetFamilies.calledOnce).to.be.true; + expect(mockRes.statusValue).to.equal(200); + expect(mockRes.json.calledWith(mockFamilies)).to.be.true; + }); + + it('handles error', async () => { + const mockError = new Error('mock error'); + const mockGetFamilies = sinon.stub(CritterbaseService.prototype, 'getFamilies').rejects(mockError); + + const { mockReq, mockRes, mockNext } = getRequestHandlerMocks(); + const requestHandler = getFamilies(); + + try { + await requestHandler(mockReq, mockRes, mockNext); + expect.fail(); + } catch (actualError) { + expect(actualError).to.equal(mockError); + expect(mockGetFamilies.calledOnce).to.be.true; + } + }); +}); diff --git a/api/src/paths/critter-data/family/index.ts b/api/src/paths/critter-data/family/index.ts index d745a51ca3..5525c7f568 100644 --- a/api/src/paths/critter-data/family/index.ts +++ b/api/src/paths/critter-data/family/index.ts @@ -3,8 +3,10 @@ import { Operation } from 'express-openapi'; import { PROJECT_PERMISSION, SYSTEM_ROLE } from '../../../constants/roles'; import { authorizeRequestHandler } from '../../../request-handlers/security/authorization'; import { CritterbaseService, ICritterbaseUser } from '../../../services/critterbase-service'; +import { getLogger } from '../../../utils/logger'; // TODO: Put this all into an existing endpoint +const defaultLog = getLogger('paths/critter-data/family'); export const GET: Operation = [ authorizeRequestHandler((req) => { @@ -75,7 +77,12 @@ export function getFamilies(): RequestHandler { }; const cb = new CritterbaseService(user); - const result = await cb.getFamilies(); - return res.status(200).json(result); + try { + const result = await cb.getFamilies(); + return res.status(200).json(result); + } catch (error) { + defaultLog.error({ label: 'getFamilies', message: 'error', error }); + throw error; + } }; }