1

I have two files:

Simple Express app: app.js

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

and an app.test.js

import axios from 'axios';

beforeAll( () => {
// Probably here I should start the server, but how?
});

test("test-my-api", async () => {
  const response = await axios.get("http://localhost:3000")
  expect(response.data).toBe("Hello World!")
}")

How can I run the app before testing the requests to the app in a secure manner? How is it done professionally?

brame
  • 13
  • 4
  • I would refactor to separate _creating_ and _starting_ the app, then you can use [Supertest](https://www.npmjs.com/package/supertest) to start the app for you as part of the testing process (as well as providing an API for making assertions - see https://stackoverflow.com/a/62992056/3001761). At the moment, just importing `app.js` starts the app. – jonrsharpe May 25 '22 at 14:16
  • That makes sense, but the way I imagined it is not possible? Does supertest starts the server or just mock it? – brame May 25 '22 at 14:20
  • Per the docs and as I quoted in the linked answer - _"if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports"_. It's not a mock, it lets you make real requests to the actual app. You don't actually need to do _anything_ for what you've imagined - again, importing starts the app. – jonrsharpe May 25 '22 at 14:21
  • Okay nice, got it. Separated the app into a different file. Imported the app into tests and now I can run supertests on it. Perfect! – brame May 25 '22 at 14:43

0 Answers0