Browse Source

Enable returning body directly (#14)

pull/15/head
Kevin Mårtensson 7 years ago
committed by Luke Childs
parent
commit
03dcb004a6
  1. 3
      README.md
  2. 12
      src/index.js
  3. 15
      test/create-test-server.js

3
README.md

@ -38,6 +38,9 @@ createTestServer().then(server => {
res.send('bar');
});
// You can return a body directly too
server.get('/foo', () => 'foo');
// server.url + '/foo' and server.sslUrl + '/foo' will respond with 'bar'
});
```

12
src/index.js

@ -9,8 +9,16 @@ const createCert = require('create-cert');
const createTestServer = opts => createCert(opts && opts.certificate)
.then(keys => {
const app = express();
const get = app.get.bind(app);
const server = http.createServer(app);
const sslServer = https.createServer(keys, app);
const send = fn => (req, res) => {
new Promise(resolve => resolve(fn(req, res))).then(val => {
if (val) {
res.send(val);
}
});
};
app.set('etag', false);
@ -38,6 +46,10 @@ const createTestServer = opts => createCert(opts && opts.certificate)
})
]);
app.get = (path, fn) => {
get(path, send(fn));
};
return app.listen().then(() => app);
});

15
test/create-test-server.js

@ -91,3 +91,18 @@ test('opts.certificate is passed through to createCert()', async t => {
});
t.is(body, 'bar');
});
test('support returning body directly', async t => {
const server = await createTestServer();
server.get('/foo', () => 'bar');
server.get('/bar', () => ({ foo: 'bar' }));
server.get('/async', () => Promise.resolve('bar'));
const bodyString = (await got(server.url + '/foo')).body;
const bodyJson = (await got(server.url + '/bar', { json: true })).body;
const bodyAsync = (await got(server.url + '/async')).body;
t.deepEqual(bodyString, 'bar');
t.deepEqual(bodyJson, { foo: 'bar' });
t.deepEqual(bodyAsync, 'bar');
});

Loading…
Cancel
Save