import supertest from 'supertest'; import should from 'should/as-function'; import db from "../db"; export default class TestHelper { public static auth = { admin: {pass: 'Abc123!#', key: '5ea131671feb9c2ee0aafc9a'}, janedoe: {pass: 'Xyz890*)', key: '5ea0450ed851c30a90e70899'} } public static res = { 400: {status: 'Bad request'}, 401: {status: 'Unauthorized'}, 403: {status: 'Forbidden'}, 404: {status: 'Not found'}, } static before (done) { process.env.port = '2999'; process.env.NODE_ENV = 'test'; db.connect('test', done); } static beforeEach (server, done) { delete require.cache[require.resolve('../index')]; // prevent loading from cache server = require('../index'); db.drop(err => { // reset database if (err) return done(err); db.loadJson(require('../test/db.json'), done); }); return server } static afterEach (server, done) { server.close(done); } static request (server, done, options) { // options in form: {method, url, auth: {key/basic: 'name' or 'key'/{name, pass}}, httpStatus, req, res} let st = supertest(server); if (options.hasOwnProperty('auth') && options.auth.hasOwnProperty('key')) { options.url += '?key=' + (this.auth.hasOwnProperty(options.auth.key)? this.auth[options.auth.key].key : options.auth.key); } switch (options.method) { case 'get': st = st.get(options.url) break; case 'post': st = st.post(options.url) break; case 'put': st = st.put(options.url) break; case 'delete': st = st.delete(options.url) break; } if (options.hasOwnProperty('req')) { st = st.send(options.req); } if (options.hasOwnProperty('auth') && options.auth.hasOwnProperty('basic')) { if (this.auth.hasOwnProperty(options.auth.basic)) { st = st.auth(options.auth.basic, this.auth[options.auth.basic].pass) } else { st = st.auth(options.auth.basic.name, options.auth.basic.pass) } } st = st.expect('Content-type', /json/) .expect(options.httpStatus); if (options.hasOwnProperty('res')) { return st.end((err, res) => { if (err) return done (err); should(res.body).be.eql(options.res); done(); }); } else if (this.res.hasOwnProperty(options.httpStatus) && options.default !== false) { return st.end((err, res) => { if (err) return done (err); should(res.body).be.eql(this.res[options.httpStatus]); done(); }); } else { return st; } } }