Sept 12 2023
Setting up jest, supertest in a typescript node.Js app
express
typescript
node
node.js
jest
supertest
Setting up jest, supertest in a typescript node.Js app
- By the end of this post you will know how to setup supertest and jest for a node.Js typescript project (Sept 2023).
Table of Contents
install the following packages (9):
- install the following dev dependencies
//run in terminal
npm i -D typescript ts-jest jest @types/express @types/jest @types/node @types/supertest nodemon supertest typescript
- to create a jest.config.js file run the following in the terminal:
//run in terminal
npx ts-jest config:init
- to create a
tsconfig.json
run the following command in the terminal
tsc --init
- add the following to the
tsconfig.json
file to exclude the test files.
{
"compilerOptions": {
// your options (configure these)
},
"include": [
"./src/**/*.ts"
],
"exclude": [
"./src/**/*.test.*"
]
}
Making a basic express app
- now install express and then make a folder called
src
and inside files calledapp.ts
andserver.ts
androutes.ts
. Inapp.ts
write
//app.ts
import express from "express"
import { generalGET } from "./routes"
function createApp (){
const app = express()
app.get("/",generalGET)
return app
}
export default createApp
- in
routes.ts
write
import { Request, Response } from "express"
export const generalGET = (req:Request,res:Response)=>{
res.status(200)
res.json({success:true})
}
- and in
server.ts
write
import createApp from "./app"
const app = createApp()
app.listen(5000,()=>{console.log("server is running on port 5000")})
- add the following commands to
package.json
// in scripts section
"testAll":"jest --watchAll",
"build":"tsc",
"start":"node dist/server.js",
"server":"nodemon src/server.ts"
Writing a basic test
- update the typescript config file tscongig.json outDir to
./dist
. Also make a file calledapp.test.ts
in/src
and inside put the code.
import request from "supertest"
import createApp from "../app"
const app = createApp()
describe('route / method GET',()=>{
describe('when the route is called',()=>{
it('should respond with 200 status and json body',async()=>{
const response = await request(app).get("/")
expect(response.status).toBe(200)
expect(response.headers['content-type']).toEqual(expect.stringContaining('json'))
})
})
})
- now run
npm run testAll
to run the test.
Conclusion
Thank you for reading. This blog has explained the basic setup for testing a node.Js typescript application using supertest and jest as of September 2023.
You have reached the end of this post. Thank you for reading!