Skip to content

Commit

Permalink
Added family index request handler try/catch and unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyQuartech committed Aug 29, 2023
1 parent 888bf4e commit 5e4df5e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
41 changes: 41 additions & 0 deletions api/src/paths/critter-data/family/index.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
});
11 changes: 9 additions & 2 deletions api/src/paths/critter-data/family/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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;
}
};
}

0 comments on commit 5e4df5e

Please sign in to comment.