|
| 1 | +/** |
| 2 | + * This script records the http requests (requests / response with body and headers) |
| 3 | + * so that they could be mocked for unit test. |
| 4 | + * This task is automated, this way, you don't have to bother to do it manually ! ;-) |
| 5 | + * |
| 6 | + * For the moment, I request the github API via topheman-apis-proxy (direct request gives encoded results, which might |
| 7 | + * be because of https or gzip which aren't managed yet by nock). |
| 8 | + */ |
| 9 | + |
| 10 | +const nock = require('nock'); |
| 11 | +const request = require('superagent'); |
| 12 | +const fs = require('fs'); |
| 13 | +const path = require('path'); |
| 14 | + |
| 15 | +const OUTPUT_PATH = './test/fixtures/http.json'; |
| 16 | + |
| 17 | +nock.recorder.rec({ |
| 18 | + output_objects: true, |
| 19 | + enable_reqheaders_recording: true, |
| 20 | + dont_print: true |
| 21 | +}); |
| 22 | + |
| 23 | +const uris = [ |
| 24 | + '/users/topheman', |
| 25 | + '/users/topheman/repos?page=1&per_page=15&sort=stars', |
| 26 | + '/users/topheman/repos?page=2&per_page=15&sort=stars', |
| 27 | + '/users/topheman/repos?page=3&per_page=15&sort=stars', |
| 28 | + '/users/topheman/followers', |
| 29 | + '/search/users?q=tophe' |
| 30 | +]; |
| 31 | + |
| 32 | +const promises = uris.map((uri) => { |
| 33 | + return request.get('http://localhost:8000/github' + uri) |
| 34 | +}); |
| 35 | + |
| 36 | +Promise.all(promises) |
| 37 | + .then(() => { |
| 38 | + const nockCallObjects = nock.recorder.play(); |
| 39 | + if (nockCallObjects.length > 0) { |
| 40 | + // bellow some processing to cleanup the mock so that they could be correctly used (according to your use-case, it could differ a little) |
| 41 | + const output = nockCallObjects.map((item) => { |
| 42 | + item.scope = 'http://localhost'; // change the host name (avoid CORS), and protocol (superagent-mocker considers ":" as wildcard, so you can't put a port) |
| 43 | + item.path = item.path.replace(/^\/github/,''); // remove the leading "/github" (in topheman-apis-proxy), so that relative url will be used |
| 44 | + console.log(item.path); |
| 45 | + return item; |
| 46 | + }); |
| 47 | + fs.writeFileSync(OUTPUT_PATH, JSON.stringify(output)); |
| 48 | + console.log('Saved in ', OUTPUT_PATH); |
| 49 | + process.exit(0); |
| 50 | + } |
| 51 | + throw new Error('No results'); |
| 52 | + }) |
| 53 | + .catch(error => console.log('[ERROR]', error.message)); |
0 commit comments