Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supertest augmented assert #3946

Merged
merged 3 commits into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions app/api/utils/specs/supertestExtensions.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// @ts-ignore
import Test from 'supertest/lib/test';
import { extendSupertest } from '../supertestExtensions';

describe('assertStatus', () => {
const mockError = new Error('mock error');
const assertStatusMock = jest.fn().mockReturnValue(mockError);
beforeEach(() => {
Test.prototype._assertStatus = assertStatusMock;
extendSupertest();
});

it('should use the original method', () => {
const result = Test.prototype._assertStatus(0, {});
expect(assertStatusMock).toHaveBeenCalledWith(0, {});
expect(result).toBe(mockError);
});

describe('when the assert fails', () => {
it('should add the body for a 400 code', async () => {
const result = Test.prototype._assertStatus(200, {
status: 400,
text: JSON.stringify('validation error'),
});
await expect(result.message).toMatch('validation error');
expect(result.stack).toBeUndefined();
});
});
});
24 changes: 24 additions & 0 deletions app/api/utils/supertestExtensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Response } from 'supertest';
// @ts-ignore
import Test from 'supertest/lib/test';

function extractStatusDebugInfo(res: Response): string {
try {
return JSON.stringify(JSON.parse(res.text), null, 2);
} catch (e) {
return res.text;
}
}

export function extendSupertest() {
const { _assertStatus } = Test.prototype;

Test.prototype._assertStatus = function extendedAssertStatus(status: number, res: Response) {
const err: Error = _assertStatus(status, res);
if (err) {
err.message += `\n ${extractStatusDebugInfo(res)}`;
delete err.stack;
}
return err;
};
}
3 changes: 3 additions & 0 deletions app/api/utils/testingRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { Response as SuperTestResponse } from 'supertest';

import errorHandlingMiddleware from 'api/utils/error_handling_middleware';
import languageMiddleware from 'api/utils/languageMiddleware';
import { extendSupertest } from './supertestExtensions';

extendSupertest();

const iosocket = jasmine.createSpyObj('socket', ['emit']);

Expand Down