UNPKG

3.2 kBJavaScriptView Raw
1"use strict";
2
3const passport = require('passport');
4const express = require('express');
5const http = require('http');
6const setup = require('./setup');
7
8/**
9 * @oaram {} name name of test class
10 * @oaram {} config config
11 * @oaram {} callback function to call once setting up is done
12 */
13function setupTester(name, config, callback)
14{
15 describe(name, function ()
16 {
17 let app;
18 let server;
19 let extraHeaders = {};
20 let cfg;
21
22 beforeEach(async function ()
23 {
24 // reset passport
25 // passport library itself is one big globlal state
26 // without resetting, it saves old state; will call out of date serializers etc.
27 passport._strategies = {};
28 passport._serializers = [];
29 passport._deserializers = [];
30 passport.init();
31
32 app = express();
33 cfg = typeof config === 'object' ? config : await config();
34 setup(app, cfg);
35 server = app.listen(0);
36 });
37
38 afterEach(async function ()
39 {
40 server.close();
41 });
42
43 function endpoint()
44 {
45 return `http://localhost:server.address().port/`;
46 }
47
48 function request(method, path, headers = {}, body = '')
49 {
50 path = '/api/accounts' + path;
51 return new Promise((resolve) =>
52 {
53 if (typeof body === 'object')
54 {
55 headers['content-type'] = 'application/json';
56 body = JSON.stringify(body, null, 2);
57 }
58 const options = {
59 host: 'localhost',
60 port: server.address()
61 .port,
62 method,
63 path,
64 headers: Object.assign({}, extraHeaders, headers)
65 };
66 // `http://localhost:8080/${path}`
67 const req = http.request(options, (res) =>
68 {
69 let data = new Buffer(0);
70
71 res.on('data', (chunk) =>
72 {
73 data += chunk;
74 });
75 res.on('end', () =>
76 {
77 try
78 {
79 data = JSON.parse(data);
80 }
81 catch (e)
82 {
83 console.log(e.stack, data)
84 }
85 for (let header in res.headers)
86 {
87 if (header === 'set-cookie')
88 {
89 extraHeaders['cookie'] = res.headers[header];
90 }
91 }
92 console.log(method, path, res.statusCode, res.statusCode != 200 ? body : '', res.statusCode != 200 ? data : '')
93 resolve({
94 status: res.statusCode,
95 headers: res.headers,
96 data
97 });
98 });
99 });
100 req.write(body);
101 req.end();
102 });
103 }
104
105 function getconfig()
106 {
107 return cfg;
108 }
109
110 callback({
111 endpoint,
112 request,
113 getconfig
114 });
115 });
116}
117
118const CachedCollection = require('node-collections-boilerplate/CachedCollection');
119const NoSearch = require('node-collections-boilerplate/search/NoSearch');
120const MemoryStorage = require('node-collections-boilerplate/storage/MemoryStorage');
121
122function createUsers(array)
123{
124 return CachedCollection.create(new MemoryStorage({
125 array
126 }), new NoSearch({}), CachedCollection);
127}
128
129module.exports = setupTester;
130module.exports.createUsers = createUsers;