👟
[Express]JestのみでE2Eに近いテスト
index.ts
import express from "express";
import hello from "./hello";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", hello);
const port = process.env.PORT || 4000;
app.listen(port, () => {
const url = `http://localhost:${port}`;
console.log(`------------------------------------------------------`);
console.log(`🚀 Server ready at ${url}`);
console.log(`------------------------------------------------------`);
});
hello.ts
import { Request, Response } from "express";
const hello = (req: Request, res: Response) => {
return res.status(200).json({ message: "Hello World!" });
};
export default hello;
hello.test.ts
import { Request, Response } from "express";
import hello from "./hello";
it("Hello World!", async () => {
const req = {} as Request;
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
} as jest.MockedObject<Response>;
hello(req, res);
expect(res.status.mock.calls[0][0]).toBe(200);
expect(res.json.mock.calls[0][0]).toEqual({ message: "Hello World!" });
});
Discussion