Skip to content

Simple express project with vitest

Course: Testing in the MERN Stack - chapter 6

Code - https://github.com/100xdevs-cohort-2/week-24-testing/tree/main/4-express-with-vitest

  • Init express app
npm init -y
npx tsc --init
npm install express @types/express zod
  • Update tsconfig
"rootDir": "./src",
"outDir": "./dist"
  • Write a simple src/index.ts file
import express from "express";
import { z } from "zod";
export const app = express();
app.use(express.json());
const sumInput = z.object({
a: z.number(),
b: z.number()
})
app.post("/sum", (req, res) => {
const parsedResponse = sumInput.safeParse(req.body)
if (!parsedResponse.success) {
return res.status(411).json({
message: "Incorrect inputs"
})
}
const answer = parsedResponse.data.a + parsedResponse.data.b;
res.json({
answer
})
});
app.get("/sum", (req, res) => {
const parsedResponse = sumInput.safeParse({
a: Number(req.headers["a"]),
b: Number(req.headers["b"])
})
if (!parsedResponse.success) {
return res.status(411).json({
message: "Incorrect inputs"
})
}
const answer = parsedResponse.data.a + parsedResponse.data.b;
res.json({
answer
})
});

💡 We’re not doing an app.listen here. This is because we dont want the app to actually start when the tests are running. Usually you create a bin.ts file or main.ts file that imports app and actually listens on a port

  • Install vitest
npm i -D vitest
  • Add a simple test/index.test.ts file
import { expect, test } from 'vitest'
test('true === true', () => {
expect(true).toBe(true)
})
  • Add a script to test in package.json
"test": "vitest"

  • Add supertest
npm i supertest @types/supertest
  • Update test - Notice all we had to do was update the imports. vitest is highly compatible with the jest api
$1b