Server-Render like a Pro /w Redux-First Router in 10 steps
at medium.com▼11 up and 3 down, posted by
11 up and 3 down, posted by
Here's an example:
// server/index.js
async function main(skip) {
if (skip) return;
... rest of main ...
}
main(!!module.parent).catch(console.error);
export default main;
module.parent exists when you require in a module, in this case index, say for testing... but not when you execute the module directly `node server/index` for example.
by wrapping your main logic in a function with a skip parameter, if you load the `./index.js` inside `index.test.js` it won't start your server process... in this way you can override whatever modules are used, and test that logic.
So it's another way to accomplish what you might do with supertest right: *server/index.js:* ``` export default function startServer() { const app = express() // ... regular app.use stuff etc const server = http.createServer(app) if (process.env.NODE_ENV !== 'test') { server.listen(process.env.PORT || 80, () => { console.log('Listening on %j', server.address()) }) return server } ``` *__tests__/server.js:* ``` import request from 'supertest' import startServer from '../server' it('REQUEST: /', async () => { const server = startServer() const path = '/' const res = await request(server).get(path) expect(res.status).toEqual(200) }) ``` ??