server.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import child_process from 'child_process';
  2. import tape from 'tape';
  3. import _test from 'tape-promise';
  4. import http from 'http';
  5. import socketclient from 'socket.io-client';
  6. const tapetest = _test(tape);
  7. const serverhost = 'localhost',
  8. serverport = 2424,
  9. server = child_process.fork('build/server.js');
  10. tapetest('test server', async function testServer(t) {
  11. let client;
  12. try {
  13. await waitPro();
  14. const data = await requestPro(`http://${serverhost}:${serverport}`);
  15. t.equal(data, 'working', 'received message from server');
  16. }
  17. catch(e) {
  18. console.log('error somewhere', e);
  19. t.fail('error somewhere');
  20. }
  21. t.end();
  22. server.kill();
  23. });
  24. function waitPro(n = 1000) {
  25. return new Promise(function pro(resolve, reject) {
  26. setTimeout(resolve, n);
  27. });
  28. }
  29. function requestPro(reqopts, data) {
  30. return new Promise(function prot(resolve, reject) {
  31. try {
  32. let req = http.request(reqopts, function received(resp) {
  33. let str = '';
  34. resp.on('data', function p(part) {
  35. str += part;
  36. });
  37. resp.on('end', function done() {
  38. if( resp.statusCode >= 400 && resp.statusCode <= 599 ) {
  39. reject(str);
  40. }
  41. else {
  42. resolve(str);
  43. }
  44. });
  45. });
  46. req.on('error', function err(ee) {
  47. reject(ee);
  48. });
  49. if( data ) {
  50. req.write(data);
  51. }
  52. req.end();
  53. }
  54. catch(e) {
  55. reject(e);
  56. }
  57. });
  58. }
  59. function responsePro(socket, evt, wait = 3000) {
  60. return new Promise(function pro(resolve, reject) {
  61. let to = setTimeout(reject.bind(null, 'socket event TIMEOUT ' + evt), wait);
  62. socket.once(evt, function (a) {
  63. clearTimeout(to);
  64. resolve(a);
  65. });
  66. });
  67. }