Archived
2
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
definma-api/src/helpers/test.ts

90 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-04-27 11:44:28 +02:00
import supertest from 'supertest';
import should from 'should/as-function';
import db from "../db";
export default class TestHelper {
public static auth = {
2020-04-29 12:10:27 +02:00
admin: {pass: 'Abc123!#', key: '000000000000000000001003'},
janedoe: {pass: 'Xyz890*)', key: '000000000000000000001002'},
user: {pass: 'Xyz890*)', key: '000000000000000000001001'}
2020-04-27 11:44:28 +02:00
}
public static res = {
400: {status: 'Bad request'},
401: {status: 'Unauthorized'},
403: {status: 'Forbidden'},
404: {status: 'Not found'},
2020-05-06 14:39:04 +02:00
500: {status: 'Internal server error'}
2020-04-27 11:44:28 +02:00
}
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;
}
}
}