Skip to content

Commit

Permalink
Supertest setup (#24)
Browse files Browse the repository at this point in the history
Setup supertest to test http endpoints. 

Split `index.ts` to `server.ts` with `listen` and `app.ts` with
endpoints. This is done, so testing of endpoints will be possible
without calling `listen` (that way supertest can assign its own port,
also no need to worry about closing down the server).

It turn out that imports of `ts` files need to end with `.js`, otherwise
they will not work after `tsc`. See `server.ts`

---------

Co-authored-by: Karol Wąsowski <wasowski02@protonmail.com>
  • Loading branch information
mikolaj-pirog and Kwasow authored Mar 23, 2023
1 parent fa7d715 commit 069ac9e
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 10 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ jobs:
- name: Start server
run: |
yarn install
yarn start &
sleep 10
yarn test
- name: Upload coverage reports to Codecov
env:
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "module",
"license": "MIT",
"scripts": {
"start": "tsc && node dist/index.js",
"start": "tsc && node dist/server.js",
"build": "tsc",
"test": "jest src/tests --coverage --config package.json",
"lint": "eslint --ext '.js,.ts,.tsx' src/",
Expand All @@ -26,6 +26,7 @@
"eslint-plugin-promise": "^6.0.0",
"husky": "^8.0.0",
"prettier": "2.8.4",
"supertest": "^6.3.3",
"ts-jest": "^29.0.5",
"typescript": "4.9.5"
},
Expand All @@ -39,6 +40,7 @@
"testEnvironment": "node",
"collectCoverageFrom": [
"src/*.ts"
]
],
"preset": "ts-jest"
}
}
8 changes: 8 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import express from 'express'

export const app = express()
export const port = 42069

app.get('/test', (req, res) => {
res.send('Hello from typescript express!')
})
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { app, port } from './app.js'

app.listen(port, () => {
console.log(`[server]: Server is running at localhost:${port}`)
})
12 changes: 12 additions & 0 deletions src/tests/app.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { app } from '../app'

import request from 'supertest'

test('Simple test', (done) => {
request(app)
.get('/test')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect('Hello from typescript express!')
.end(done)
})
6 changes: 0 additions & 6 deletions src/tests/index.test.ts

This file was deleted.

0 comments on commit 069ac9e

Please sign in to comment.