service.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import {fork} from 'child_process';
  2. import tape from 'tape';
  3. import _test from 'tape-promise';
  4. import http from 'http';
  5. const tapetest = _test(tape);
  6. tapetest('service', async function testService(t) {
  7. const server = fork('build/service.js'),
  8. connstring = 'http://localhost:8080';
  9. try {
  10. await waitPro();
  11. const data = await requestPro(connstring + '/');
  12. console.log('data', data);
  13. }
  14. catch(e) {
  15. console.log('error somewhere', e);
  16. t.fail('error somewhere');
  17. }
  18. server.kill();
  19. t.end();
  20. });
  21. function waitPro(n = 1000) {
  22. return new Promise(function pro(resolve, reject) {
  23. setTimeout(resolve, n);
  24. });
  25. }
  26. function requestPro(reqopts, data) {
  27. return new Promise(function prot(resolve, reject) {
  28. try {
  29. let req = http.request(reqopts, function received(resp) {
  30. let str = '';
  31. resp.on('data', function p(part) {
  32. str += part;
  33. });
  34. resp.on('end', function done() {
  35. if( resp.statusCode >= 400 && resp.statusCode <= 599 ) {
  36. reject(str);
  37. }
  38. else {
  39. resolve(str);
  40. }
  41. });
  42. });
  43. if( data ) {
  44. req.write(data);
  45. }
  46. req.end();
  47. }
  48. catch(e) {
  49. reject(e);
  50. }
  51. });
  52. }