Skip to content

Commit

Permalink
Enable returning body directly (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevva authored and lukechilds committed Feb 16, 2018
1 parent 107b58e commit 03dcb00
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -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'
});
```
Expand Down
12 changes: 12 additions & 0 deletions src/index.js
Expand Up @@ -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);

Expand Down Expand Up @@ -38,6 +46,10 @@ const createTestServer = opts => createCert(opts && opts.certificate)
})
]);

app.get = (path, fn) => {
get(path, send(fn));
};

return app.listen().then(() => app);
});

Expand Down
15 changes: 15 additions & 0 deletions test/create-test-server.js
Expand Up @@ -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');
});

0 comments on commit 03dcb00

Please sign in to comment.