Created
September 8, 2025 18:33
-
-
Save joewebber/a9b2e271bb3076c07248048ddc8c25bb to your computer and use it in GitHub Desktop.
Mocking Express middleware using Sinon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import express from "express"; | |
| import middleware from "./middleware.js"; | |
| const app = express(); | |
| const PORT = 3000; | |
| app.use(express.json()); | |
| app.use((req, res, next) => { | |
| middleware.checkAuthHeader(req, res, next); | |
| }); | |
| app.get("/", async (req, res) => { | |
| return res.status(200).json({ success: true }); | |
| }); | |
| if (process.env.NODE_ENV !== "test") { | |
| app.listen(PORT, () => { | |
| console.log(`Server is running on http://localhost:${PORT}`); | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { describe, it, beforeEach, afterEach } from "node:test"; | |
| import assert from "node:assert"; | |
| import request from "supertest"; | |
| import sinon from "sinon"; | |
| import app from "./app.js"; | |
| import middleware from "./middleware.js"; | |
| describe("Endpoint tests", () => { | |
| const middlewareStub = sinon.stub(middleware, "checkAuthHeader"); | |
| beforeEach(() => { | |
| middlewareStub.callsFake((_, __, next) => { | |
| next(); | |
| }); | |
| }); | |
| afterEach(async () => { | |
| middlewareStub.reset(); | |
| }); | |
| it("should return 200", async () => { | |
| await request(app) | |
| .get("/") | |
| .expect(200) | |
| .then((response) => { | |
| assert.deepStrictEqual(response.body, { | |
| success: true, | |
| }); | |
| }); | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const SECRET_KEY = process.env.SECRET_KEY; | |
| const checkAuthHeader = (req, res, next) => { | |
| const authHeader = req.headers["authorization"]; | |
| const token = authHeader && authHeader.split(" ")[1]; | |
| if (!token) return res.status(401).send(); | |
| if (token !== SECRET_KEY) return res.status(401).send(); | |
| next(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment