From c5d31dba56d669c0df0209761c43c5a6ac7cec4a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 28 Dec 2017 13:59:22 +0100 Subject: Tests directories refractor --- server/tests/utils/requests/requests.ts | 92 +++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 server/tests/utils/requests/requests.ts (limited to 'server/tests/utils/requests/requests.ts') diff --git a/server/tests/utils/requests/requests.ts b/server/tests/utils/requests/requests.ts new file mode 100644 index 000000000..52b7a4c29 --- /dev/null +++ b/server/tests/utils/requests/requests.ts @@ -0,0 +1,92 @@ +import * as request from 'supertest' + +function makeGetRequest (url: string, path: string) { + return request(url) + .get(path) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function makePostUploadRequest (options: { + url: string, + path: string, + token: string, + fields: { [ fieldName: string ]: any }, + attaches: { [ attachName: string ]: any }, + statusCodeExpected?: number +}) { + if (!options.statusCodeExpected) options.statusCodeExpected = 400 + + const req = request(options.url) + .post(options.path) + .set('Accept', 'application/json') + + if (options.token) req.set('Authorization', 'Bearer ' + options.token) + + Object.keys(options.fields).forEach(field => { + const value = options.fields[field] + + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + req.field(field + '[' + i + ']', value[i]) + } + } else { + req.field(field, value) + } + }) + + Object.keys(options.attaches).forEach(attach => { + const value = options.attaches[attach] + req.attach(attach, value) + }) + + return req.expect(options.statusCodeExpected) +} + +function makePostBodyRequest (options: { + url: string, + path: string, + token?: string, + fields: { [ fieldName: string ]: any }, + statusCodeExpected?: number +}) { + if (!options.statusCodeExpected) options.statusCodeExpected = 400 + + const req = request(options.url) + .post(options.path) + .set('Accept', 'application/json') + + if (options.token) req.set('Authorization', 'Bearer ' + options.token) + + return req.send(options.fields) + .expect(options.statusCodeExpected) +} + +function makePutBodyRequest (options: { + url: string, + path: string, + token: string, + fields: { [ fieldName: string ]: any }, + statusCodeExpected?: number +}) { + if (!options.statusCodeExpected) options.statusCodeExpected = 400 + + const req = request(options.url) + .put(options.path) + .set('Accept', 'application/json') + + if (options.token) req.set('Authorization', 'Bearer ' + options.token) + + return req.send(options.fields) + .expect(options.statusCodeExpected) +} + +// --------------------------------------------------------------------------- + +export { + makeGetRequest, + makePostUploadRequest, + makePostBodyRequest, + makePutBodyRequest +} -- cgit v1.2.3