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 -ynpx tsc --initnpm install express @types/express zod- Update tsconfig
"rootDir": "./src","outDir": "./dist"- Write a simple
src/index.tsfile
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.tsfile ormain.tsfile that imports app and actually listens on a port
- Install vitest
npm i -D vitest- Add a simple
test/index.test.tsfile
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.
vitestis highly compatible with the jest api
$1b