service.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {fork} from 'child_process';
  2. import tape from 'blue-tape';
  3. import http from 'http';
  4. tape.test('service', function testService(t) {
  5. const server = fork('build/service.js'),
  6. connstring = 'http://localhost:8080';
  7. waitPro()
  8. .then(function done(a) {
  9. return requestPro(connstring + '/')
  10. .then(function done(data) {
  11. console.log('data', data);
  12. return JSON.parse(data);
  13. })
  14. })
  15. .catch(function (e) {
  16. console.log('error somewhere', e);
  17. t.fail('error somewhere');
  18. })
  19. .then(function done(a) {
  20. server.kill();
  21. t.end();
  22. });
  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. if( data ) {
  47. req.write(data);
  48. }
  49. req.end();
  50. }
  51. catch(e) {
  52. reject(e);
  53. }
  54. });
  55. }